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?
The rfind() method finds the last occurrence of the specified value. The rfind() method returns -1 if the value is not found. The rfind() method is almost the same as the rindex() method.
Use the str. rsplit() method with maxsplit set to 1 to split a string and get the last element. The rsplit() method splits from the right and will only perform a single split when maxsplit is set to 1 .
First, we have printed the original string and the split word. We then performed the partition function to divide the string. This function will get a string after the substring occurrence. After performing the partition function on the initialized string, print the result in the last line of code.
A simple solution to find the last index of a character in a string is using the rfind() function, which returns the index of the last occurrence in the string where the character is found and returns -1 otherwise.
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)[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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With