Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #63109 > unrolled thread
| Started by | Chris Angelico <rosuav@gmail.com> |
|---|---|
| First post | 2014-01-04 16:18 +1100 |
| Last post | 2014-01-04 16:18 +1100 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Strange behaviour with a for loop. Chris Angelico <rosuav@gmail.com> - 2014-01-04 16:18 +1100
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2014-01-04 16:18 +1100 |
| Subject | Re: Strange behaviour with a for loop. |
| Message-ID | <mailman.4889.1388812744.18130.python-list@python.org> |
On Sat, Jan 4, 2014 at 3:03 PM, Sean Murphy <mhysnq1964@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
Back to top | Article view | comp.lang.python
csiph-web