Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get everything after last character occurrence python

Tags:

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?

like image 738
twigg Avatar asked Jan 14 '15 11:01

twigg


People also ask

How do you find the last occurrence of a character in a string in Python?

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.

How do you split the last element in Python?

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 .

How do I extract a string after a specific string in Python?

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.

How can we check the last occuring index of a particular character in a string?

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.


2 Answers

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'
like image 130
Burhan Khalid Avatar answered Oct 13 '22 17:10

Burhan Khalid


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.

like image 20
Bhargav Rao Avatar answered Oct 13 '22 15:10

Bhargav Rao