简体   繁体   English

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

[英]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.

相关问题 如何在 Python 中最后一次出现非数字字符后获取所有数字 - How to get all numbers after the last occurrence of a non numeric character in Python 即使有重复,也要在一个字符之后获取所有内容。 蟒蛇 - Get everything after a character, even when there are repeats. Python 替换字符串中给定关键字最后一次出现后的所有内容 - Replace everything after the last occurrence of the given keywords in a string Python 替换第一个和最后一个字符之间的所有内容 - Python replace everything in between first and last character 在Python中最后一次出现给定字符之后,找到字符串字符的最简单方法是什么? - What is the easiest way of finding the characters of a string after the last occurrence of a given character in Python? 通过在python中另一个字符之前最后出现的字符来解析字符串 - parse string by the last occurrence of the character before another character in python Python在索引后找到第一个出现的字符 - Python find first occurrence of character after index 第三次出现字符python后去掉字符串 - Strip string after third occurrence of character python 在Python中获取最后一个'/'或'\\\\'字符 - Get the last '/' or '\\' character in Python Python:删除特定字符(,)之后的所有内容 - Python : Remove everything after a specific character (,)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM