【问题标题】:Replacing repeated word in a string (python) [duplicate]替换字符串中的重复单词(python)[重复]
【发布时间】:2017-12-20 08:41:53
【问题描述】:

我希望能够将字符串中的每个 'hello' 替换为 'newword' 一次。

在第一个输出中:

' Hello word word new word word word word hello' 

只有第一个 hello 会被替换。

在第二个输出中:

'Hello word word hello word word word new word'

只会替换第二个hello。

例如:

l = ' Hello word word hello word word word hello'

w = 'hello'

l=l.replace(w,'newword',1)

上面的代码只是替换了第一个hello。

我怎样才能用保留第一个 hello 来替换第二个 hello。 有没有办法通过(索引)做到这一点?

感谢您的帮助和提示。

【问题讨论】:

    标签: python string


    【解决方案1】:

    可以迭代查找下一次出现的索引, 从上一次出现的索引开始。 一旦有了要替换的事件的起始索引, 您可以在该索引之前获取字符串的前缀, 并对后缀应用 1 个替换项。 返回前缀和替换后缀的串联。

    def replace_nth(s, word, replacement, n):
        """
        >>> replace_nth("Hello word word hello word word word hello", "hello", "rep", 1)
        'Hello word word rep word word word hello'
    
        >>> replace_nth("Hello word word hello word word word hello", "hello", "rep", 2)
        'Hello word word hello word word word rep'
    
        >>> replace_nth("Hello word word hello word word word hello", "hello", "rep", 3)
        'Hello word word hello word word word hello'
    
        >>> replace_nth("", "hello", "rep", 3)
        ''
    
        """
        index = -1
        for _ in range(n):
            try:
                index = s.index(word, index + 1)
            except ValueError:
                return s
    
        return s[:index] + s[index:].replace(word, replacement, 1)
    

    【讨论】:

      【解决方案2】:

      您可以将句子拆分为其组成词,并仅替换给定计数的单词,将计数保留为itertools.count

      from itertools import count
      
      def replace(s, w, nw, n=1):
          c = count(1)
          return ' '.join(nw if x==w and next(c)==n else x for x in s.split())
      
      s = ' Hello word word hello word word word hello'
      
      print replace(s, 'hello', 'new word')
      # Hello word word new word word word word hello
      
      print replace(s, 'hello', 'new word', n=2)
      # Hello word word hello word word word new word
      

      只要您替换用空格分隔的单词而不是任意子字符串,这应该可以工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-05
        • 2021-08-01
        • 1970-01-01
        • 2016-06-06
        • 1970-01-01
        • 2020-11-09
        • 2015-01-01
        • 1970-01-01
        相关资源
        最近更新 更多