This seems really simple but I can't figure it out. I have a string of bits in a string format and want to convert it to a binary format. I assumed placing the string inside of the bin() function would work but it doesn't.
string = "01101"
print(bin(string))
-
Take a look: devdungeon.com/content/working-binary-data-pythonGiovanni– Giovanni2020年09月14日 07:31:43 +00:00Commented Sep 14, 2020 at 7:31
2 Answers 2
string = "01101"
print(bin(int(string,2)))
Sign up to request clarification or add additional context in comments.
Comments
It depends what you mean by binary format.
Here's a few examples of what you can do:
>>> int('01101', 2)
13
>>> number = 13
>>> bin(number)
'0b1101'
>>> oct(number)
'0o15'
>>> hex(number)
'0xd'
>>> f'{number:08b}'
'00001101'
answered Sep 14, 2020 at 7:32
Wolph
80.4k12 gold badges142 silver badges152 bronze badges
1 Comment
Tom Lightfoot
Didn't realize you could specify a base within the int function, thanks.
lang-py