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`
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With