Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add tag around matches paragraph in Python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading