Remove Last instance of a character and rest of a string

后端 未结 4 992
予麋鹿
予麋鹿 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:44

    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.

提交回复
热议问题