Reputation: 13
I'm having a hard time understanding this for loop. I am new with python so I don't understand what exactly is happening here. The code is for html escaping.
My question is: How does the for loop get executed? why does for(i,o) in (.........) how is this ever true? how does it know there is an & symbol in the string s?
def escape_html(s):
for(i,o) in (("&", "&"),(">",">"),('<','<'),('"',""")):
s=s.replace(i,o)
return s
print escape_html("hello&> this is do\"ge")
Upvotes: 1
Views: 369
Reputation: 8409
First you need to understand tuple unpacking.
(a, b) = ("foo", 1)
This expressions assigns "foo"
to a
and 1
b
. The same syntax can be used inside of loops to unpack the elements of iterator object you are looping over.
So for each element of your loop you are unpacking an element of the nested tuple ( which is iterable ).
def escape_html(s):
for (i,o) in (("&", "&"),(">",">"),('<','<'),('"',""")):
s = s.replace(i,o)
return s
Unrolling the loop gives you something like this:
def escape_html(s):
s = s.replace("&", "&")
s = s.replace(">",">")
s = s.replace('<','<')
s = s.replace('"',""")
return s
Upvotes: 2
Reputation: 122007
The syntax
for x, y in z:
Means "unpack the 2-tuples in the iterable z
into two variables x
and y
for each iteration of the for
loop".
This doesn't have to be True
; you're thinking of a while
loop:
while True:
which is designed for iterating until some condition is met, whereas a for
loop is for working through items in an iterable.
And it doesn't know that any of the first characters in the pairs will be in the argument s
, but replace
doesn't throw an error if it isn't.
Upvotes: 1
Reputation: 336128
Does this help?
>>> for(i,o) in (("&", "&"),(">",">"),('<','<'),('"',""")):
... print "i: {}, o: {}".format(i,o)
...
i: &, o: &
i: >, o: >
i: <, o: <
i: ", o: "
During each iteration of the loop, one element of the iterator is picked; so for the first iteration, that element is the tuple ("&", "&")
. That tuple is then unpacked into the variables i
and o
.
Upvotes: 1