Remove Last instance of a character and rest of a string

后端 未结 4 939
予麋鹿
予麋鹿 2020-12-10 14:41

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

4条回答
  •  有刺的猬
    2020-12-10 15:19

    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'
    

提交回复
热议问题