0

how can I replace a string in a line of text but only one instance of it?

let's say I have s = "foo bar foo", and I want to replace the second foo with baz, how can I do that?

thanks, Chaf

Chaf
  • 3
  • 1
  • duplicate? http://stackoverflow.com/questions/1883980/find-the-nth-occurrence-of-substring-in-a-string – yoopoo Jul 04 '14 at 08:01

4 Answers4

1

Pythonic way:

"baz".join(s.rsplit("foo", 1))

Intuitive way:

old_string = "foo bar foo"
i = old_string.rfind("foo")
new_string = old_string[:i] + "baz" + old_string[i + len("foo"):]
Omer Eldan
  • 1,757
  • 1
  • 11
  • 10
  • The intuitive way replaces the last foo. If there more than two foos, the second won't be replaced. – yoopoo Jul 04 '14 at 07:14
0

If you have more occurance of foo and want to replace all

>>> s = "clar foo bar foo bar foo"
>>> s = s.split('foo', 1)
>>> print s[0] + 'foo' + s[1].replace('foo','baz')
clar foo bar baz bar baz
Holt
  • 36,600
  • 7
  • 92
  • 139
sundar nataraj
  • 8,524
  • 2
  • 34
  • 46
0

Here is a general purpose solution that will replace words based on index:

def replace_via_index(string, to_replace=None):
    if not to_replace:
        to_replace = dict()
    string = string.split(' ')

    for i, n in enumerate(string):
        if i in to_replace:
            string[i] = to_replace[i]

    return ''.join(n + ' ' for n in string)
idiot.py
  • 388
  • 2
  • 7
0

There are two steps to go: 1. find the nth occurrence 2. replace this occurrence

 s = 'foo bar foo'
 n = s.find('foo')
 print s[:n+1] + s[n+1:].replace('foo', 'baz')
 # 'foo bar baz'
ichbinblau
  • 4,507
  • 5
  • 23
  • 36