So I am making my own little script to detect some markdown notations in a variable. Now there are two issues.
- First of all, my current approach does not work when using the markdown as following (I am referring to the question mark):
**am I working**?
- Aside from that does the code look quite messy and I am pretty sure that it can be done more efficiently.
I was wondering as to what could be a better way to do what I am trying.
I want to add that I have looked for packages but these wont work in my case as I only want to allow bold, italic, underline and escaping (**bold**, _italic_ and __underline__).
My current code:
description = "**one more test** _just to be sure_ \*hi\* apparently __underline broke__?"
for word in description.split(" "):
if word.startswith("**"):
description = description.replace(word, f'<b>{word.replace("**", "", 1)}')
word = word.replace("**", "", 1)
if word.endswith("**") and not word.endswith("\**"):
description = description.replace(word, f'{word.replace("**", "", 1)}</b>')
word = word.replace("**", "", 1)
if word.startswith("*"):
description = description.replace(word, f'<i>{word.replace("*", "", 1)}')
word = word.replace("*", "", 1)
if word.endswith("*") and not word.endswith("\*"):
description = description.replace(word, f'{word.replace("*", "", 1)}</i>')
word = word.replace("*", "", 1)
if word.startswith("__"):
description = description.replace(word, f'<u>{word.replace("__", "", 1)}')
word = word.replace("__", "", 1)
if word.endswith("__") and not word.endswith("\__"):
description = description.replace(word, f'{word.replace("__", "", 1)}</u>')
word = word.replace("__", "", 1)
if word.startswith("_"):
description = description.replace(word, f'<i>{word.replace("_", "", 1)}')
word = word.replace("_", "", 1)
if word.endswith("_") and not word.endswith("\_"):
description = description.replace(word, f'{word.replace("_", "", 1)}</i>')
word = word.replace("_", "", 1)
print(description)