我在Python中有以下函数:
def escape_html(s):
for(i, o) in (("&", "&"),
(">", ">"),
(">", ">"),
(">", ">")):
s = s.replace(i,o)
return s
print escape_html('"hello, & = &"')
我不明白 for 中的那些"i"和"o"变量
有人可以帮助了解这是如何工作的吗?
谢谢!
首先,您需要了解元组解包。我们正在迭代元组的元组,因此每次迭代都会生成一个内部元组。这些元组中的每一个都有两个元素,因此可以方便地解压缩它们,并使用一些花哨的语法在一个语句中分配给两个变量:
for pair in (("&", "&"),
(">", ">"),
(">", ">"),
(">", ">")):
print(pair)
(i, o) = pair
print(i)
print(o)
输出:
('&', '&')
&
&
('>', '>')
>
>
('>', '>')
>
>
('>', '>')
>
>
元组解包可以直接在 for 循环中完成,以获得更大的便利:
for (i, o) in (("&", "&"),
(">", ">"),
(">", ">"),
(">", ">")):
print(i)
print(o)
输出:
&
&
>
>
>
>
>
>
至于replace
方法:
>>> help('abc'.replace)
Help on built-in function replace:
replace(...) method of builtins.str instance
S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
>>> 'abc def abc.'.replace('abc', '123')
'123 def 123.'
>>> s = '"hello, & = &"'
>>> s = s.replace("&", "&")
>>> s
'"hello, & = &"'