Remove substring only at the end of string

后端 未结 11 706
再見小時候
再見小時候 2020-12-23 13:23

I have a bunch of strings, some of them have \' rec\'. I want to remove that only if those are the last 4 characters.

So in other words I have



        
11条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-23 13:54

    Taking inspiration from @David Foster's answer, I would do

    def _remove_suffix(text, suffix):
        if text is not None and suffix is not None:
            return text[:-len(suffix)] if text.endswith(suffix) else text
        else:
            return text
    

    Reference: Python string slicing

提交回复
热议问题