Georg Brandl | 1f7fffb | 2010-10-15 15:57:45 +0000 | [diff] [blame] | 1 | """ |
| 2 | General functions for HTML manipulation. |
| 3 | """ |
| 4 | |
| 5 | |
| 6 | _escape_map = {ord('&'): '&', ord('<'): '<', ord('>'): '>'} |
| 7 | _escape_map_full = {ord('&'): '&', ord('<'): '<', ord('>'): '>', |
| 8 | ord('"'): '"', ord('\''): '''} |
| 9 | |
| 10 | # NB: this is a candidate for a bytes/string polymorphic interface |
| 11 | |
| 12 | def escape(s, quote=True): |
| 13 | """ |
| 14 | Replace special characters "&", "<" and ">" to HTML-safe sequences. |
| 15 | If the optional flag quote is true (the default), the quotation mark |
Senthil Kumaran | d71bbf9 | 2011-09-13 07:14:13 +0800 | [diff] [blame] | 16 | characters, both double quote (") and single quote (') characters are also |
| 17 | translated. |
Georg Brandl | 1f7fffb | 2010-10-15 15:57:45 +0000 | [diff] [blame] | 18 | """ |
| 19 | if quote: |
| 20 | return s.translate(_escape_map_full) |
| 21 | return s.translate(_escape_map) |