howto print binary number

castironpi at gmail.com castironpi at gmail.com
Wed May 7 20:05:25 EDT 2008


On May 7, 4:03 pm, Joel Bender <j... at cornell.edu> wrote:
> > Python 3.0 has such a formatting operation, but Python 2.x does not.  
> > However it's not hard to write.
>
> Indeed.  Refraining from using named lambdas:
>
>      >>> def bin(x):
>      ...     return ''.join(x & (1 << i) and '1' or '0' for i in
>      ...         range(7,-1,-1))
>      ...
>      >>> bin(12)
>      '00001100'
>      >>> bin(63)
>      '00111111'
>
> It would be nice to have str(x, 2) like int(x, 2), but there are bigger
> fish in pond.

+1 str( x, base ) +1



More information about the Python-list mailing list