2017-07-15 91 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)