Remove substring only at the end of string

后端 未结 11 704
再見小時候
再見小時候 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:36

    You could use a regular expression as well:

    from re import sub
    
    str = r"this is some string rec"
    regex = r"(.*)\srec$"
    print sub(regex, r"\1", str)
    
    0 讨论(0)
  • 2020-12-23 13:37

    Here is a one-liner version of Jack Kelly's answer along with its sibling:

    def rchop(s, sub):
        return s[:-len(sub)] if s.endswith(sub) else s
    
    def lchop(s, sub):
        return s[len(sub):] if s.startswith(sub) else s
    
    0 讨论(0)
  • 2020-12-23 13:38
    
    def remove_trailing_string(content, trailing):
        """
        Strip trailing component `trailing` from `content` if it exists.
        """
        if content.endswith(trailing) and content != trailing:
            return content[:-len(trailing)]
        return content
    
    0 讨论(0)
  • 2020-12-23 13:40

    use:

    somestring.rsplit(' rec')[0]
    
    0 讨论(0)
  • 2020-12-23 13:41

    Using more_itertools, we can rstrip strings that pass a predicate.

    Installation

    > pip install more_itertools
    

    Code

    import more_itertools as mit
    
    
    iterable = "this is some string rec".split()
    " ".join(mit.rstrip(iterable, pred=lambda x: x in {"rec", " "}))
    # 'this is some string'
    
    " ".join(mit.rstrip(iterable, pred=lambda x: x in {"rec", " "}))
    # 'this is some string'
    

    Here we pass all trailing items we wish to strip from the end.

    See also the more_itertools docs for details.

    0 讨论(0)
  • 2020-12-23 13:46

    As kind of one liner generator joined:

    test = """somestring='this is some string rec'
    this is some string in the end word rec
    This has not the word."""
    match = 'rec'
    print('\n'.join((line[:-len(match)] if line.endswith(match) else line)
          for line in test.splitlines()))
    """ Output:
    somestring='this is some string rec'
    this is some string in the end word 
    This has not the word.
    """
    
    0 讨论(0)
提交回复
热议问题