tags:

views:

151

answers:

3

In Ruby i do so

asd = 123
asd = '%b' % asd # => "1111011"
+6  A: 

in Python >= 2.6 with bin():

asd = bin(123) # => '0b1111011'

To remove the leading 0b you can just take the substring bin(123)[2:].

bin(x)
Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

New in version 2.6.

Felix Kling
You could also remove the leading '0b' by doing bin(123).strip('0b').
Justin Peel
@Justin, you should use `lstrip` instead of `strip` as the latter will strip any `0`s from the end of the string as well as the front (thereby changing the value). The slice is probably a better way to go, as it will only ever remove those two characters from the string.
tgray
@tgray Yes, I agree now that I have thought about it a little more.
Justin Peel
+7  A: 

you can also do string formatting, which doesn't contain '0b':

>>> '{:b}'.format(123)            #{0:b} in python 2.6
'1111011'
SilentGhost
Link: http://docs.python.org/library/string.html#format-specification-mini-language
Felix Kling
Pretty cool! But it should be `'{0:b}'.format(123)`, and it is for python version ≥ 2.6 only.
Olivier
Great, it is that i find out.
edtsech
@Oliver: comment says it. `'{:b}'` is python 2.7 and 3.1 version.
SilentGhost
@Oliver ...No...
Beau Martínez
A: 

bin() works, as Felix mentioned. For completeness, you can go the other way as well.

>>> int('01101100',2)
108
>>> bin(108)
'0b1101100'
>>> bin(108)[2:]
'1101100'
Charles Merriam