0

So at school, we are meant to be making a binary and decimal converter. So far I have discovered the bin() function and it gives me roughly what I need:

bin(10)
#0b1010  

However, I was wandering how I would go about removing the 0b at the beginning so that I am left with simply 1010.

Does anyone actually know what the 0b means?

3 Answers3

4

The 0b means it is binary. And, to remove it, simply do this:

>>> bin(10)
'0b1010'
>>> bin(10)[2:]
'1010'
>>> bin(12345)
'0b11000000111001'
>>> bin(12345)[2:]
'11000000111001'
>>>

This solution takes advantage of Python's slice notation.

Community
  • 1
  • 1
2

I am not sure exactly what you are asking, but I think its "How do i trim the start of a string off"

And you can do that with slicing:

>>> s = "I am a string"
>>> s[5:]
'a string'

So in your case it would be:

>>> bin(10)[2:]
'1010'
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
1

There is another way to convert a number to binary without the 0b at the beginning

>>> '{0:0b}'.format(10)
'1010'

This question will be helpful to you Converting integer to binary in python

Community
  • 1
  • 1
kyle k
  • 5,134
  • 10
  • 31
  • 45