0

I have some strings that have the following characters: &, <, and >. In the project I am working on, these are reserved characters and need to be escaped using &amp; for &, &lt; for <, etc. What is this best approach to this? Currently thinking of either multiple if statements that look for it one-by-one using str.replace() or somehow using a dictionary where the keys are the characters to be replaced and the values are what to replace them with.

1 Answer 1

3

You can use html.escape function(html is part of python standard library) to replace the special characters &, < and > with &amp;&lt;&gt;

>>> import html
>>>
>>> html.escape("&<>")
'&amp;&lt;&gt;'
>>>
>>> help(html.escape)
Help on function escape in module html:

escape(s, quote=True)
    Replace special characters "&", "<" and ">" to HTML-safe sequences.
    If the optional flag quote is true (the default), the quotation mark
    characters, both double quote (") and single quote (') characters are also
    translated.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.