1

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

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.