howley
howley

Reputation: 665

Replace multiple characters in string using dictionary in python

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.

Upvotes: 0

Views: 241

Answers (1)

user459872
user459872

Reputation: 24602

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.

Upvotes: 3

Related Questions