I’m trying to add a <p>...</p> tag for each paragraph so I make this code
import re
text = """How did saw get created?
Saw's Jigsaw Killer"""
fs = re.findall("^[^?]+$", text, re.M)
text = re.sub(f"({'|'.join(fs)})", r"<p>\1</p>", text)
print(text)
the output is
How did saw get created?
<p>Saw's Jigsaw Killer</p>
until now everything works fine, but when my text contain () the tag is not added
example
How did saw get created?
Saw's Jigsaw (1990) Killer
I got the same text without adding tag
>Solution :
You have to escape your string:
>>> re.sub(f"({'|'.join(re.escape(s) for s in fs)})", r"<p>\1</p>", text)
"How did saw get created?\n<p>Saw's Jigsaw (1990) Killer</p>"