Remove Last instance of a character and rest of a string

Tags: ,

If I have a string as follows:


Is there a clean way, with RegEx, to return: foo_bar_one_two?

I know I can use split, pop and join for this, but I’m looking for a cleaner solution.


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

Which behaves like this:

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

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

Source: stackoverflow