python: rstrip one exact string, respecting order

前端 未结 6 2123
挽巷
挽巷 2020-12-16 09:16

Is it possible to use the python command rstrip so that it does only remove one exact string and does not take all letters separately?

I was confused w

6条回答
  •  余生分开走
    2020-12-16 09:57

    Define a helper function:

    def strip_suffix(s, suf):
        if s.endswith(suf):
            return s[:len(s)-len(suf)]
        return s
    

    or use regex:

    import re
    suffix = ".txt"
    s = re.sub(re.escape(suffix) + '$', '', s)
    

提交回复
热议问题