0
Using same string and replacing different names
import re str = "My name is David. Hi David.Amy is my name" pattern = r"David" pattern1= r"Amy" newstr = re.sub(pattern, "Amy", str,1) str2= re.sub(pattern1, "David", str) print(newstr) print(str2)
1 Respuesta
+ 4
If your goal is to switch the names then this will do:
str = "My name is David. Hi David. Amy is my name"
pattern = r"(David)(.*)(Amy)"
newstr = Iregex.sub(pattern, r"\3\2\1", str)
print(newstr)