これは非常に単純なPythonです。
forループは、反復可能オブジェクトから個々のアイテムを解凍します。したがって、たとえば、次のような何かを行うことができます。
>>> c = [('a', 'b', 'c'), ('d', 'e', 'f')]
>>> for i, j, k in c:
... print i, j, k
...
a b c
d e f
あなたの場合(i, o)
、タプルのタプルからの値が入力されています。次に、のインスタンスはi
の値に置き換えられますo
。この関数は、html特殊文字をそれぞれを表すエンティティに置き換えています。
>>> s = 'foo & bar'
>>> s = s.replace('&', '&')
>>> s
'foo & bar'
この関数は同等に実行しています:
def escape_html(s):
s = s.replace("&","&")
s = s.replace(">", ">")
s = s.replace("<", "<")
s = s.replace('"', """)
return s
適切なデバッガーを使用する代わりに、いくつかのprintステートメントを追加して、何が起こっているかを確認してください。
def escape_html(s):
print "ORIGINAL STRING: %s" % (s)
for (i, o) in (("&","&"),(">", ">"),("<", "<"),('"', """)):
print "\t(i, o) = ('%s', '%s')" % (i, o)
s = s.replace(i , o)
print "\ts = %s" % (s, )
print
return s
mystring = """<h3>This is a test</h3><script>alert("I hacked you!");</script>"""
print escape_html(mystring)
出力
ORIGINAL STRING: <h3>This is a test</h3><script>alert("I hacked you!");</script>
(i, o) = ('&', '&')
s = <h3>This is a test</h3><script>alert("I hacked you!");</script>
(i, o) = ('>', '>')
s = <h3>This is a test</h3><script>alert("I hacked you!");</script>
(i, o) = ('<', '<')
s = <h3>This is a test</h3><script>alert("I hacked you!");</script>
(i, o) = ('"', '"')
s = <h3>This is a test</h3><script>alert("I hacked you!");</script>
<h3>This is a test</h3><script>alert("I hacked you!");</script>