I have a string like this:
Hi. My name is _John_. I am _20_ years old.
and I'd like to convert it into this:
Hi. My name is <b>John</b>. I am <b>20</b> years old.
I did something like this but no luck.
import re
text = "Hi. My name is _John_. I am _20_ years old."
pattern = "(.*)(\_)(.*)(\_)(.*)"
re.sub(pattern, r'\1<b>\3</b>\5', text)
'Hi. My name is _John_. I am <b>20</b> years old.'
What is wrong with the pattern? Why is it not seeing the first bold text?
Any help would be appreciated. Thanks.
Change to:
pattern = "_([^_]*)_"
re.sub(pattern, r'<b>\1</b>', text)
Also see this example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With