Reputation: 3993
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?
Upvotes: 35
Views: 56611
Reputation: 52101
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)[1]
>>> a
' 1462'
>>> a.strip()
'1462'
The rsplit solution, however, will not work if there is no occurrence of the character, since then there will be only one element in the array returned.
Upvotes: 25
Reputation: 174622
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'
Upvotes: 76