Possible Duplicate:
What's the easiest way to escape HTML in Python?
What's the easiest way to HTML escape characters in Python? I would like to take a list of items and iterate over them, having them changed to HTML escaped characters.
Possible Duplicate:
What's the easiest way to escape HTML in Python?
What's the easiest way to HTML escape characters in Python? I would like to take a list of items and iterate over them, having them changed to HTML escaped characters.
Python standard library has cgi
module, which provides escape
function.
See: http://docs.python.org/library/cgi.html#functions
Template engines tend to make your code cleaner and easier to maintain. For example, you can pass the list to the template engine and do the iteration inside the template:
t = Template('{% for item in items %}{{ item }}\n{% endfor %}')
result = t.render(dict(items=some_list))
Most template engines will escape html by default. There are quite a few to choose from, when I'm not not using Django, may favorite is jinja2.
See http://wiki.python.org/moin/Templating for other alternatives.
Try something like this (untested, just a sample):
html_convert = {"<": "<", ">": ">", "\"": """, "&": "&"} #Etc.
html_text = "<div id=\"idk\">Something truly interesting & fun...</div>"
html_list = [char for char in html_text]
for char in html_list:
if char in html_convert:
char = html_convert[char]
html_escaped_text = "".join(html_list)