Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Last instance of a character and rest of a string

Tags:

python

regex

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.

like image 284
Paul Avatar asked Sep 11 '13 00:09

Paul


3 Answers

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]]).

like image 151
Tadeck Avatar answered Sep 27 '22 23:09

Tadeck


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'
like image 44
paxdiablo Avatar answered Sep 27 '22 22:09

paxdiablo


Similar the the rsplit solution, rpartition will also work:

result = my_string.rpartition("_")[0]

You'll need to watch out for the case where the separator character is not found. In that case the original string will be in index 2, not 0.

doc string:

rpartition(...)

S.rpartition(sep) -> (head, sep, tail)

Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S.

like image 29
nakedfanatic Avatar answered Sep 27 '22 21:09

nakedfanatic