Python for循环行为问题

时间:2016-04-01 21:54:05

标签: python for-loop

我无法理解为什么这段代码没有给我预期的结果,即替换像>这样的特殊字符。他们的特殊序列如>

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")

特别是因为我从this Udacity课程

复制粘贴此代码

代码提供此输出

>
<
"
&
test&test

而不是用它们的转义序列替换这些特殊字符。

我知道Python已经内置了对escape_html函数的支持,但是我想知道我做错了什么?

1 个答案:

答案 0 :(得分:3)

您忽略了str.replace()返回值

s.replace(i,o)

s设置为结果:

s = s.replace(i,o)

字符串是不可变的,因此所有字符串方法都返回 new 字符串对象。

接下来,您必须将('&','&amp;')替换件移至顶部;否则,您将替换&&gt;&lt;中的&quot;

演示:

>>> 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