Strange behaviour with a for loop.
Chris Angelico
rosuav at gmail.com
Sat Jan 4 00:18:55 EST 2014
On Sat, Jan 4, 2014 at 3:03 PM, Sean Murphy <mhysnq1964 at icloud.com> wrote:
> filenames = sys.argv[1:]
>
> for filename in filenames:
> print ("filename is: %s\n" %filename)
versus
> filenames = sys.argv[1]
>
> for filename in filenames:
> print ("filename is: %s\n" % filename)
The first one is slicing sys.argv, so it returns another list. For
instance, sys.argv might be:
['foo.py', 'test', 'zxcv']
in which case sys.argv[1:] would be:
['test', 'zxcv']
which is still a list. But sys.argv[1] is a single string:
'test'
Now, when you use that in a for loop, you iterate over it. Iterating
over a list yields its items, as you'd expect. Iterating over a string
yields its characters. That's why you see it spelled out. Instead of
iterating over a list of file names, you're iterating over a single
file name, which isn't (in this case) all that useful.
Does that explain what you're seeing?
ChrisA
More information about the Python-list
mailing list