Remove Last instance of a character and rest of a string

result = my_string.rsplit('_', 1)[0]

Which behaves like this:

>>> my_string = 'foo_bar_one_two_three'
>>> print(my_string.rsplit('_', 1)[0])
foo_bar_one_two

See in the documentation entry for str.rsplit([sep[, maxsplit]]).


One way is to use rfind to get the index of the last _ character and then slice the string to extract the characters up to that point:

>>> s = "foo_bar_one_two_three"
>>> idx = s.rfind("_")
>>> if idx >= 0:
...     s = s[:idx]
...
>>> print s
foo_bar_one_two

You need to check that the rfind call returns something greater than -1 before using it to get the substring otherwise it'll strip off the last character.

If you must use regular expressions (and I tend to prefer non-regex solutions for simple cases like this), you can do it thus:

>>> import re
>>> s = "foo_bar_one_two_three"
>>> re.sub('_[^_]*$','',s)
'foo_bar_one_two'

Tags:

Python

Regex