user3207914
user3207914

Reputation: 13

Python for loop with a tuple in it

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 (("&", "&amp;"),(">","&gt;"),('<','&lt;'),('"',"&quot;")):  
    s=s.replace(i,o)
return s



print escape_html("hello&> this is do\"ge")

Upvotes: 1

Views: 369

Answers (3)

Stephen Diehl
Stephen Diehl

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 (("&", "&amp;"),(">","&gt;"),('<','&lt;'),('"',"&quot;")):
    s = s.replace(i,o)
  return s

Unrolling the loop gives you something like this:

def escape_html(s):
  s = s.replace("&", "&amp;")
  s = s.replace(">","&gt;")
  s = s.replace('<','&lt;')
  s = s.replace('"',"&quot;")
  return s

Upvotes: 2

jonrsharpe
jonrsharpe

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

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

Does this help?

>>> for(i,o) in (("&", "&amp;"),(">","&gt;"),('<','&lt;'),('"',"&quot;")):
...     print "i: {}, o: {}".format(i,o)
...
i: &, o: &amp;
i: >, o: &gt;
i: <, o: &lt;
i: ", o: &quot;

During each iteration of the loop, one element of the iterator is picked; so for the first iteration, that element is the tuple ("&", "&amp;"). That tuple is then unpacked into the variables i and o.

Upvotes: 1

Related Questions