【问题标题】:How to replace the some characters from the end of a string?如何替换字符串末尾的一些字符?
【发布时间】:2011-04-10 04:08:50
【问题描述】:

我想替换 Python 字符串末尾的字符。我有这个字符串:

 s = "123123"

我想用x 替换最后一个2。假设有一个方法叫replace_last

 r = replace_last(s, '2', 'x')
 print r
 1231x3

有没有内置的或简单的方法可以做到这一点?

【问题讨论】:

    标签: python string replace


    【解决方案1】:

    这正是rpartition 函数的用途:

    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.
    

    我写了这个函数来展示如何在你的用例中使用rpartition

    def replace_last(source_string, replace_what, replace_with):
        head, _sep, tail = source_string.rpartition(replace_what)
        return head + replace_with + tail
    
    s = "123123"
    r = replace_last(s, '2', 'x')
    print r
    

    输出:

    1231x3
    

    【讨论】:

    • 这个解决方案有缺陷。如果没有找到 replace_what 字符串,则将 replace_with 插入到字符串的开头。
    【解决方案2】:

    使用正则表达式函数re.sub替换字符串末尾的单词

    import re
    s = "123123"
    s = re.sub('23$', 'penguins', s)
    print s
    

    打印:

    1231penguins
    

    import re
    s = "123123"
    s = re.sub('^12', 'penguins', s)
    print s
    

    打印:

    penguins3123
    

    【讨论】:

    • 对于问题中给出的示例:r = re.sub(r"2[^2]$", "x", s)
    • 问题不是询问字符串的结尾,而是从字符串后面替换。
    【解决方案3】:

    这是少数没有左右版本的字符串函数之一,但我们可以使用一些具有左右版本的字符串函数来模仿其行为。

    >>> s = '123123'
    >>> t = s.rsplit('2', 1)
    >>> u = 'x'.join(t)
    >>> u
    '1231x3'
    

    >>> 'x'.join('123123'.rsplit('2', 1))
    '1231x3'
    

    【讨论】:

    • +1:除了比公认的解决方案更短之外,该解决方案的优点是可以根据自己的意愿从右侧进行尽可能多的替换,只需更改第二个参数的值rsplit()。当我去寻找解决这个问题的方法时,这对我来说是一个优势,因为否则我将不得不使用循环来进行多次替换。
    【解决方案4】:
    >>> s = "aaa bbb aaa bbb"
    >>> s[::-1].replace('bbb','xxx',1)[::-1]
    'aaa bbb aaa xxx'
    

    第二个例子

    >>> s = "123123"
    >>> s[::-1].replace('2','x',1)[::-1]
    '1231x3'
    

    【讨论】:

    • 这仅适用于回文,修复:source[::-1].replace(old[::-1], new[::-1], count)[::-1]
    • @Kresimir -- 很好地解决了回文问题。太棒了! (我个人最喜欢这种 [::-1] 方法,因为可以使用replace() normal sytax 进行正向和反向替换)。
    【解决方案5】:

    当想要的匹配在字符串的末尾时,re.sub 来救援。

    >>> import re
    >>> s = "aaa bbb aaa bbb"
    >>> s
    'aaa bbb aaa bbb'
    >>> re.sub('bbb$', 'xxx', s)
    'aaa bbb aaa xxx'
    >>> 
    

    【讨论】:

      【解决方案6】:

      这是一个基于对您的问题的简单解释的解决方案。更好的答案需要更多信息。

      >>> s = "aaa bbb aaa bbb"
      >>> separator = " "
      >>> parts = s.split(separator)
      >>> separator.join(parts[:-1] + ["xxx"])
      'aaa bbb aaa xxx'
      

      更新

      (在看到编辑后的问题后)另一个非常具体的答案。

      >>> s = "123123"
      >>> separator = "2"
      >>> parts = s.split(separator)
      >>> separator.join(parts[:-1]) + "x" + parts[-1]
      '1231x3'
      

      更新 2

      有更好的way to do this。礼貌@mizipzor

      【讨论】:

        【解决方案7】:
        txt = "123123"
        txt = txt[::-1]
        txt = txt.replace("2", "*", 1)
        txt = txt[::-1]
        

        【讨论】:

        • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
        【解决方案8】:

        我得到了一个棘手的答案,但它的效率不够

        
            >>> fname = '12345.png.pngasdfg.png'
            >>> suffix = '.png'
            >>> fname_rev = fname[::-1]
            >>> suffix_rev = suffix[::-1]
            >>> fullname_rev = fname_rev.replace(suffix_rev, '', 1)
            >>> fullname = fullname_rev[::-1]
            >>> fullname '12345.png.pngasdfg'
        
        

        内置函数 replace() 接受三个参数 str.replace(old, new, max_time) 所以你可以从原始字符串中删除最后一个匹配的字符串

        【讨论】:

          【解决方案9】:

          对于第二个例子,我推荐rsplit,因为它使用起来非常简单,直接达到了目的。这是它的一个小功能:

          def replace_ending(sentence, old, new):
              if sentence.endswith(old):
                  i = sentence.rsplit(old,1)
                  new_sentence =new.join(i)
                  return new_sentence
              return sentence
          
          print(replace_ending("aaa bbb aaa bbb", "bbb", "xxx")) 
          

          输出:

          aaa bbb aaa xxx

          【讨论】:

            【解决方案10】:

            有一种方法可以处理函数replace 以使其向后工作。 这个想法是从头到尾读取字符串、要替换的文本和新文本。逻辑保持不变。

            这是基于使用[::-1] 向后切换字符串的方式。

            例如:

            >>> a = "123 456 123 456 123 456"
            >>> print(a)
            123 456 123 456 123 456
            

            我们想用“abc”替换最后一个(或两个,或n)个“123”

            >>> res = a[::-1].replace("123"[::-1], "abc"[::-1], 1)[::-1]
            >>> print(res)
            123 456 123 456 abc 456
            

            这可以作为一个行为与替换完全相同的函数。

            def replace_right(text, old, new, count=-1):
                """
                Return a copy with all occurrences of substring old replaced by new starting from right.
                """
                return text[::-1].replace(old[::-1], new[::-1], count)[::-1]
            

            执行:

            >>> replace_right(a, "123", "abc", 1)
            '123 456 123 456 abc 456'
            
            >>> replace_right(a, "123", "abc", 2)
            '123 456 abc 456 abc 456'
            

            【讨论】:

              【解决方案11】:

              有一个非常简单的方法可以做到这一点,按照我的步骤操作

              str = "stay am stay am  delete am"
              #  want to remove the last am
              str = str[:str.rfind('am')]
              print(str)
              

              首先,我们找到am最后一次出现的索引号,然后取第 0 个索引到该特定索引。

              【讨论】:

              • 谢谢,但不是“删除”,而是“替换”
              • Hii @Freewind 删除后,您可以在该位置连接任何字符串? CODE str = "stay am stay am delete vvamvv gggg" # want to remove the last am str = str[:str.rfind('am')] + "REPLACED" + str[(str.rfind('am') + len("am")):] print(str)
              猜你喜欢
              • 2017-08-02
              • 1970-01-01
              • 2020-08-12
              • 2012-02-03
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多