Skip to main content

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*

9
  • 8
    Or just use format(integer, 'b'). bin() is a debugging tool, specifically aimed at producing the Python binary integer literal syntax, format() is meant to produce specific formats. Commented Dec 10, 2015 at 10:21
  • 1
    @MartijnPieters Thank you very much for mentioning it. I've adjusted my solutution. How do you know that bin() is a debugging tool aimed at producing the Python binary integer literal syntax? I couldn't find that in the documentation. Commented Dec 10, 2015 at 10:36
  • 3
    From the documentation: The result is a valid Python expression. It's aim is to produce a Python expression, not to produce end-user representations. The same applies to oct() and hex(). Commented Dec 10, 2015 at 10:37
  • 6
    More alternatives: If you are going to make the width dynamic, instead of str.zfill() you could use str.format() or format() with a dynamic second argument: '{0:0{1}b}'.format(x, n) or format(b, '0{}b'.format(n)). Commented Dec 10, 2015 at 10:41
  • @MartijnPieters Wow, thank you very much for this input! I didn't know that this was possible with format. However, I think my current answer with zfill is easier to read and understand than the dynamic second argument, so I'll keep that. Commented Dec 10, 2015 at 10:45