[英]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()
函数,它大致满足了我的需求:
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
. 但是,我一直在徘徊如何从一开始就删除
0b
,以便我只剩下1010
。
Does anyone actually know what the 0b
means? 有人真的知道
0b
意味着什么吗?
The 0b
means it is binary. 0b
表示它是二进制的。 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 . 该解决方案利用了Python的slice表示法 。
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 还有另一种方法将数字转换为二进制,开头不带
0b
>>> '{0:0b}'.format(10)
'1010'
This question will be helpful to you Converting integer to binary in python 你这个问题将有助于在Python转换为二进制整数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.