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 & for &, < 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.
Add a comment
|
1 Answer
You can use html.escape function(html is part of python standard library) to replace the special characters &, < and > with &<>
>>> import html
>>>
>>> html.escape("&<>")
'&<>'
>>>
>>> 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.