-1

my code below works fine.

import re

def mycontent(text: str):
    netx = text
    urls = re.findall("MyText", netx)
    for i in urls:
        netx = netx.replace(i, "MyReplaceText")
    
    return netx

I want to combine this word with a few more words. How can I do that? Thank you.

import re

def mycontent(text: str):
    netx = text
    urls = re.findall("MyText", "MyText1" tnetx)
    for i in urls:
        netx = netx.replace(i, "MyReplaceText", "MyText1Replace"")

    return netx

I tried in the form but I couldn't get results, it didn't work.

D.L
  • 4,339
  • 5
  • 22
  • 45

1 Answers1

0

To match multiple strings, use alternatives in the regexp. Then use re.sub() with a replacement function that looks up the corresponding replacement.


def mycontent(text: str) -> str:
    replacements = {'MyText': 'MyReplacement1', 'MyText1', 'MyReplacement1'}
    return re.sub(r'MyText|MyText1', lambda m: replacements[m.group(), text]
Barmar
  • 741,623
  • 53
  • 500
  • 612