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
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
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"):]
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
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)
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'