2017-07-15 143 views
0

我希望能够将字符串中的每个'hello'替换为'newword'一次。替换字符串中的重复单词(python)

在第一输出:

' Hello word word new word word word word hello' 

第一喂仅将被替换。

在第二输出:

'Hello word word hello word word word new word' 

第二喂仅将被替换。

例如:

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

w = 'hello' 

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

以上只需更换第一喂的代码。

我如何能够保持第一个问候,以取代第二个问候。 有没有办法通过(索引)来做到这一点?

感谢您的帮助和提示。

回答

1

您可以将句子拆分成其组成的单词和在给定的数只替换词,保持计数与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 

只要你替换了由空格分隔的单词,而不是任意的字符串,这应该工作。

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)