Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make sequence of string.replace statements more readable

When I'm processing HTML code in Python I have to use the following code because of special characters.

line = string.replace(line, """, "\"")
line = string.replace(line, "'", "'")
line = string.replace(line, "&", "&")
line = string.replace(line, "&lt;", "<")
line = string.replace(line, "&gt;", ">")
line = string.replace(line, "&laquo;", "<<")
line = string.replace(line, "&raquo;", ">>")
line = string.replace(line, "&#039;", "'")
line = string.replace(line, "&#8220;", "\"")
line = string.replace(line, "&#8221;", "\"")
line = string.replace(line, "&#8216;", "\'")
line = string.replace(line, "&#8217;", "\'")
line = string.replace(line, "&#9632;", "")
line = string.replace(line, "&#8226;", "-")

It seems there will be much more such special characters I have to replace. Do you know how to make this code more elegant?

thank you

like image 942
xralf Avatar asked Aug 18 '26 23:08

xralf


1 Answers

REPLACEMENTS = [
    ("&quot;", "\""),
    ("&apos;", "'"),
    ...
    ]
for entity, replacement in REPLACEMENTS:
    line = line.replace(entity, replacement)

Note that string.replace is simply available as a method on str/unicode objects.

Better yet, check out this question!

The title of your question asks something different, though: optimization, i.e. making it run faster. That's a completely different problem, and will require more work.

like image 120
Thomas Avatar answered Aug 20 '26 14:08

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!