在最后一个字符出现后获取所有内容

时间:2022-08-09 00:24:23

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. I want to split a line after the last occurrence of a '-' character, my string would look like the following:

我已经看到过用其他语言提问但是找不到它的Python,也许它有一个我不知道的具体名称。我想在最后一次出现' - '字符后拆分一行,我的字符串如下所示:

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?

当一个未知数量的 - 可能存在且结束数量可以是任何长度时,我将如何实现这一目标?

2 个解决方案

#1


17  

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'

#2


4  

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'

#1


17  

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'

#2


4  

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'