If I have a string as follows:
foo_bar_one_two_three
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.
Advertisement
Answer
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]])
.