Reputation: 426
I am new to python and I want to replace same substring occurrences of a particular string with different substrings by using python. I already tried the .replace() function of python, but it replaces all the occurrences with the new substring. Example for the question is below.
string = "I am a student as well as a teacher" Here I want to replace the substring "as" with "xas" and "yas" by adding extra character to the substring. The final result should be "I am a student xas well yas a teacher"
Code that I have tried:
string = "I am a student as well as a teacher"
occurrences = re.findall("as", string)
substr = ["xas","yas"]
i = 0
for occur in occurrences:
string = string.replace(occur, substr[i])
i = i + 1`
Upvotes: 4
Views: 477
Reputation: 36370
You can inform replace how many times it should replace following way
s = "I am a student as well as a teacher"
s = s.replace("as","xxx",1)
print(s) #I am a student xxx well as a teacher
s = s.replace("as","yyy",1)
print(s) #I am a student xxx well yyy a teacher
EDIT: Replacing first as
with xas
and second as
with yas
requires different approach
s = "I am a student as well as a teacher"
repl = ["xas","yas"]
s = s.split("as")
for i in repl:
s = [i.join(s[:2])]+s[2:]
s = s[0]
print(s) #I am a student xas well yas a teacher
Note that this solution assumes number of elements of repl
is exatcly equal to number of as
in s
.
Upvotes: 1
Reputation: 51643
You can use regex as well:
substr = ["xxx","yyy"]
def replace_with(_):
"""Returns first value of substr and removes it."""
return substr.pop(0)
import re
string = "I am a student as well as a teacher"
print(re.sub("as",replace_with,string))
Output:
I am a student xxx well yyy a teacher
But the solution using str.replace() with a limit of 1 by Daweo is more elegant.
Upvotes: 2