|
12 | 12 | except AttributeError: |
13 | 13 | _StringTypes = [types.StringType] |
14 | 14 |
|
| 15 | +def __dict_replace(s, d): |
| 16 | + """Replace substrings of a string using a dictionary.""" |
| 17 | + for key, value in d.items(): |
| 18 | + s = s.replace(key, value) |
| 19 | + return s |
15 | 20 |
|
16 | 21 | def escape(data, entities={}): |
17 | 22 | """Escape &, <, and > in a string of data. |
18 | | -
|
| 23 | + |
19 | 24 | You can escape other strings of data by passing a dictionary as |
20 | 25 | the optional entities parameter. The keys and values must all be |
21 | 26 | strings; each key will be replaced with its corresponding value. |
22 | 27 | """ |
| 28 | + |
| 29 | + # must do ampersand first |
23 | 30 | data = data.replace("&", "&") |
24 | | - data = data.replace("<", "<") |
25 | | - data = data.replace(">", ">") |
26 | | - for chars, entity in entities.items(): |
27 | | - data = data.replace(chars, entity) |
28 | | - return data |
| 31 | + data = __dict_replace(data, {"<" : "<", |
| 32 | + ">" : ">", |
| 33 | + }) |
| 34 | + return __dict_replace(data, entities) |
| 35 | + |
| 36 | +def unescape(data, entities={}): |
| 37 | + """Unescape &, <, and > in a string of data. |
| 38 | +
|
| 39 | + You can unescape other strings of data by passing a dictionary as |
| 40 | + the optional entities parameter. The keys and values must all be |
| 41 | + strings; each key will be replaced with its corresponding value. |
| 42 | + """ |
| 43 | + data = __dict_replace(data, {"<" : "<", |
| 44 | + ">" : ">", |
| 45 | + }) |
| 46 | + # must do ampersand last |
| 47 | + data = data.replace("&", "&") |
| 48 | + return __dict_replace(data, entities) |
29 | 49 |
|
30 | 50 | def quoteattr(data, entities={}): |
31 | 51 | """Escape and quote an attribute value. |
|
0 commit comments