Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Convert int to binary string in Python

How do I convert an integer into a binary string in Python?

37 → '100101'

Answer*

Draft saved
Draft discarded
Cancel
5
  • 109
    Note also that it's faster to do str(bin(i))[2:] (0.369s for 1000000ops) than "{0:b}".format(i) (0.721s for 1000000ops) Commented Oct 30, 2013 at 7:55
  • 92
    @mVChr if someone's converting numbers into an ASCII binary representation, I really hope speed doesn't matter. Commented Feb 5, 2014 at 5:04
  • 43
    @mVChr: str.format() is the wrong tool anyway, you would use format(i, 'b') instead. Take into account that that also gives you padding and alignment options though; format(i, '016b') to format to a 16-bit zero-padded binary number. To do the same with bin() you'd have to add a str.zfill() call: bin(i)[2:].zfill(16) (no need to call str()!). format()'s readability and flexibility (dynamic formatting is much harder with bin()) are great tradeoffs, don't optimise for performance unless you have to, until then optimise for maintainability. Commented Dec 10, 2015 at 10:28
  • What does [2:] mean? Commented Aug 18, 2017 at 20:43
  • 15
    Of course, with python 3.6+ you can now use f"{37:b}". Commented Nov 6, 2017 at 6:48

lang-py

AltStyle によって変換されたページ (->オリジナル) /