0

I can't understand why this code is not giving me the intended results i.e replacing special characters like > with their special sequence like >

def escape_html(s):
    for (i,o) in ((">",">"),
                 ('<','&lt;'),
                 ('"','&quot;'),
                 ('&','&amp;')):
        s.replace(i,o)
    return s

print escape_html('>')
print escape_html('<')
print escape_html('"')
print escape_html("&")
print escape_html("test&test")

Specially because I am literally copy pasting this code from this Udacity lesson

The code is giving this output

>
<
"
&
test&test

instead of replacing these special characters with their escape sequences.

I am aware of the fact that Python has in built support for escape_html function, but I want to understand what am I doing wrong?

Piyush
  • 606
  • 4
  • 16
  • 38

1 Answers1

3

You are ignoring the return value of str.replace():

s.replace(i,o)

Set s to the result:

s = s.replace(i,o)

Strings are immutable, so all string methods return a new string object.

Next, you'll have to move the ('&','&amp;') replacement to the top; otherwise you'll replace the & in &gt;, &lt; and &quot;.

Demo:

>>> def escape_html(s):
...     for (i,o) in (
...             ('&','&amp;'),
...             (">","&gt;"),
...             ('<','&lt;'),
...             ('"','&quot;')):
...         s = s.replace(i,o)
...     return s
...
>>> print escape_html('>')
&gt;
>>> print escape_html('<')
&lt;
>>> print escape_html('"')
&quot;
>>> print escape_html("&")
&amp;
>>> print escape_html("test&test")
test&amp;test
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343