[Tutor] Assigning each line of text to a separate variable

Dave Angel davea at ieee.org
Thu Jul 30 23:13:22 CEST 2009


Marv Boyes wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">Hello, 
> all. This is probably embarrassingly basic, but I haven't been able to 
> find something that works.
>
> I'm working on a script that needs to manipulate a list (not 'list' in 
> the Python sense) of URLs returned in a server response. Right now, 
> I'm stripping the XML tags from that response and assigning the 
> resulting list of URLs to a variable so I can print it in the 
> terminal. So when I do, say, 'print urls' I get something like this:
>
>     http://server.com/thing1
>     http://server.com/thing2
>     http://server.com/thing3
>
> And so on. What I would _like_ to do is assign each line of that list 
> to a separate variable, so that I can format my output to be more 
> explicit; something like this:
>
>     Link to Thing1: http://server.com/thing1
>     Link to Thing2: http://server.com/thing2
>
> And so on. I know this should be extremely easy, but I appear to be 
> having some manner of mental block. Any and all guidance would be 
> greatly appreciated; many thanks in advance.
>
>
Usually, when people say they want to assign items from a list to 
separate variables, it's because they don't understand lists.  But I'll 
give you several (untested) fragments, and see if one of them comes 
close to what you really want.


Assuming URLs is your current list, and that it has exactly 3 items in it.

here, there, everwhere = URLs
      will give you those three variables, each assigned to one of the 
URL strings

print "Link to Thing1", URLs[0]
print "Link to Thing2", URLs[1]
print "Link to Thing3", URLs[2]
     lets you print them out individually, without wasting any separate 
assignments, or giving them explicit names

for index, item in enumerate(URLs):
      print "Link to Thing%s" % index,  item

      will print out your original request, and even work if you change 
the list to have 4 or 5 items

HTH

DaveA

 


More information about the Tutor mailing list