在Python中切割字符串
当我们需要在某个特定位置切割一个字符串时,我们需要知道从哪个位置开始。
比如,在这个字符串中:
>>> s = 'Your ID number is: 41233'
我想从 :
开始切割字符串,并获取后面的数字。
当然,我可以先 数一数 :
在字符串中的位置,然后再进行切割,但这样真的好吗?
当然,我可以用 s.index(':')
来找到这个位置。但这会多一个步骤,所以我想出了类似这样的做法:
>>> print s[(s.index(':')+2):]
41233
不过我总觉得这样看起来不太好。
所以我的问题是,对于一个很长的字符串,如果我想切割它,最简单、最易读的方式是什么来找到开始切割的位置?如果有简单的方法可以口头上解决这个问题,我也很想知道。
6 个回答
1
另一种方法是用 'Your ID number is: 41233'.split(':')[1].strip()
这段代码。
这里的意思是,我们有一个字符串“Your ID number is: 41233”,然后我们用“:”这个符号把它分开。分开后,左边是“Your ID number is”,右边是“ 41233”。因为我们只想要右边的部分,所以用[1]来取第二部分。最后,使用.strip()去掉前后的空格,得到的结果就是“41233”。
2
text, sep, number = 'Your ID number is: 41233'.partition(':')
print number
这个方法也可以用。不过如果字符串里没有分隔符,它不会出错。
这种解包的方法也适用于分割操作:
text, number = 'Your ID number is: 41233'.split(':',1)
2
也许你可以使用 split()
这个方法:
>>> s = 'Your ID number is: 41233'
>>> print s.split(":")[1].strip()
41233