[英]get everything after last character occurrence python
I've seen this asked in other languages but can't find it for Python, maybe it has a specific name i'm not aware of. 我已经看到过用其他语言提问但是找不到它的Python,也许它有一个我不知道的特定名称。 I want to split a line after the last occurrence of a '-' character, my string would look like the following:
我想在最后一次出现' - '字符后拆分一行,我的字符串如下所示:
POS--K 100 100 001 - 1462
I want to take the last number from this string after the last -, in this case 1462. I have no idea how to achieve this in, to achieve this when only one such character is expected I would use the following: 我想从最后一个字符串中取出最后一个数字 - 在本例中为1462.我不知道如何实现这个目的,为了实现这一点,当只有一个这样的字符被预期时我会使用以下内容:
last_number = last_number[last_number.index('-')+1:]
How would I achieve this when an unknown number of - could be present and the end number could be of any length? 当一个未知数量的 - 可能存在且结束数量可以是任何长度时,我将如何实现这一目标?
You were almost there. 你快到了。
index
selects from the left, and rindex
selects from the right: index
从左侧选择, rindex
从右侧选择:
>>> s = 'POS--K 100 100 001 - 1462'
>>> s[s.rindex('-')+1:]
' 1462'
You can do this if you want the last number after the last -
如果你想要最后一个数字,你可以这样做
-
>>> s = "POS--K 100 100 001 - 1462"
>>> a = s.split('-')[-1]
>>> a
' 1462'
>>> a.strip()
'1462'
Or as Padraic mentioned in a comment , you can use rsplit
或者如评论中提到的Padraic,您可以使用
rsplit
>>> s = "POS--K 100 100 001 - 1462"
>>> a = s.rsplit('-')[1]
>>> a
' 1462'
>>> a.strip()
'1462'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.