Can string formatting be used to convert an integer to its binary form ?
Neil Cerutti
horpner at yahoo.com
Fri Sep 29 10:47:17 EDT 2006
On 2006-09-29, Georg Brandl <g.brandl-nospam at gmx.net> wrote:
> 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.
I suppose two wrongs wouldn't make a right. ;)
--
Neil Cerutti
More information about the Python-list
mailing list