简体   繁体   中英

How to remove beginning of a string

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?

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 .

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'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM