-3

I have a string and I want to change it using regex:

import re 
s1 = "FirstName0001LastName0001"
s2 = re.sub('LastName', 'FamilyName', s1)
s2 = re.sub('FirstName', 'Contact', s1)

Expected Result s2 = "Contact0001FamilyName0001", Is there any other way to do this in one line of code?

buddemat
  • 4,552
  • 14
  • 29
  • 49
  • What's the point of the `s2 = re.sub('LastName', 'FamilyName', s1)` line? It doesn't seem relevant here (unless your expected result is wrong). Also, you probably don't need regex for this. `s2 = s1.replace("FirstName", "Contact")` is sufficient. – 41686d6564 stands w. Palestine Nov 09 '20 at 16:06
  • You do not use the first substitution result when you run `s2 = re.sub('FirstName', 'Contact', s1)`, why? – Wiktor Stribiżew Nov 09 '20 at 16:12
  • Does this answer your question? https://stackoverflow.com/questions/6116978/how-to-replace-multiple-substrings-of-a-string – buddemat Nov 09 '20 at 16:13

1 Answers1

1

I may get downvoted for doing this, but:

s1 = "FirstName0001LastName0001"
s2 = s1.replace('LastName', 'FamilyName').replace('FirstName', 'Contact')
print(s2)  # prints Contact0001FamilyName0001

You may not even need to use a re.sub regex replacement here, and you can just chain the replacement calls in a single line.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360