help with simple script and strings

James Antill james at fedoraproject.com
Sat Apr 12 20:52:06 UTC 2008


On Sat, 2008-04-12 at 13:35 -0700, John Poelstra wrote:
> I'm just getting started with python.  Curious what I need to change to 
> properly filter out only strings starting with "200"
> 
> script:
> #!/usr/bin/python
> 
> directories = ['20080412', '20080324', 'blahblah', 'latest-dir', 
> 'rawhide-20080410', 'rawhide-20080411', 'rawhide-20080412' , '20080401']
> 
> print 'directories == %s' % directories
> 
> for directory in directories:
>      print 'processing directory %s ' % directory
>      if not directory.startswith('200'):
>          directories.remove(directory)
>          print 'removed == %s' % directory
> 
> print 'directories == %s' % directories

 You can't alter things that you are iterating, the easist fix is:

for directory in directories[:]:

...the others being to create a new list of just what you want, or a
list of what needs to go and then do the .remove() calls on that (these
methods can be worth it, for large lists).

-- 
James Antill <james at fedoraproject.com>
Fedora




More information about the python-devel mailing list