Can string formatting be used to convert an integer to its binary form ?

Georg Brandl g.brandl-nospam at gmx.net
Fri Sep 29 10:36:47 EDT 2006


Neil Cerutti wrote:
> On 2006-09-29, Steve Holden <steve at holdenweb.com> wrote:
>> MonkeeSage wrote:
>>> So far as unobfuscated versions go, how about the simple:
>>> 
>>> def to_bin(x):
>>>   out = []
>>>   while x > 0:
>>>     out.insert(0, str(x % 2))
>>>     x = x / 2
>>>   return ''.join(out)
>>> 
>>> Regards,
> 
> It was surprising that
> 
>>>> i = int("111010101", 2)
> 
> is a one-way operation.
> 
>>>> s = str(i, 2)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: str() takes at most 1 argument (2 given)

str() is not only for converting integers, but all other types too.
An explicit argument for this special case is not Pythonic IMO.

Georg



More information about the Python-list mailing list