简体   繁体   中英

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. 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:

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:

>>> 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

>>> s = "POS--K    100    100    001    -    1462"
>>> a = s.rsplit('-')[1]
>>> a
'    1462'
>>> a.strip()
'1462'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM