1

I want to be able to replace each 'hello' in a string to 'newword' one time.

In the first output:

' Hello word word new word word word word hello' 

the first hello only will be replaced.

In the second output:

'Hello word word hello word word word new word'

the second hello only will be replaced.

for example :

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

w = 'hello'

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

The code above just replace the first hello.

How can I be able to replace the second hello with keeping the first hello. is there any way to do that by (index)?

Thanks for help and hints.

Ilario Pierbattista
  • 3,175
  • 2
  • 31
  • 41
S.M
  • 71
  • 5

2 Answers2

1

You can split the sentence into its constituent words and replace only the word at a given count, keeping the counts with 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

As long you're replacing words separated by whitespaces and not arbitrary substrings, this should work.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
1

You can iteratively find the index of the next occurrence, starting from the index of the previous occurrence. Once you have the start index of the occurrence you want to replace, you can take the prefix of the string before that index, and apply 1 replacement to the suffix. Return the concatenation of the prefix and the replaced suffix.

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)
janos
  • 120,954
  • 29
  • 226
  • 236