Using same string and replacing different names | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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)

26th Jul 2017, 7:40 AM
Yojit Handa
Yojit Handa - avatar
1 Answer
+ 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)
26th Jul 2017, 1:32 PM
Maya
Maya - avatar