I need to do some very quick-n-dirty input sanitizing and I would like to basically convert all <, > to <, >.
I'd like to achieve the same results as '<script></script>'.replace('<', '<').replace('>', '>') without having to iterate the string multiple times. I know about maketrans in conjunction with str.translate (ie. ) but this only converts from 1 char to another char. In other words, one cannot do something like:
inList = '<>'
outList = ['<', '>']
transform = maketrans(inList, outList)
Is there a builtin function that can do this conversion in a single iteration?
I'd like to use builtin capabilities as opposed to external modules. I already know about Bleach.
3 Answers
You can use cgi.escape()
import cgi
inlist = '<>'
transform = cgi.escape(inlist)
print transform
Output:
<>
cgi.escape(s[, quote]) Convert the characters '&', '<' and '>' in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. If the optional flag quote is true, the quotation mark character (") is also translated; this helps for inclusion in an HTML attribute value delimited by double quotes, as in . Note that single quotes are never translated.
Use html.escape() - cgi.escape() is deprecated in Python 3
import html
input = '<>&'
output = html.escape(input)
print(output)
<>&
You can define your own function that loops over the string once and replaces any characters you define.
def sanitize(input_string):
output_string = ''
for i in input_string:
if i == '>':
outchar = '>'
elif i == '<':
outchar = '<'
else:
outchar = i
output_string += outchar
return output_string
Then calling
sanitize('<3 because I am > all of you')
yields
'<3 because I am > all of you'