question about endswith()

Rafael Durán Castañeda rafadurancastaneda at gmail.com
Fri Mar 4 02:47:51 EST 2011


I think you want do this:

>>> files = ['file1.hdf', 'file2.hdf', 'file3.hdf5','file4.hdf']
>>> print(''.join(x for x in files if x.endswith('5')))
file3.hdf5
>>>

But if you need to use it later:

>>> file_hdf5 = [x for x in files if x.endswith('5')]
>>> file_hdf5
['file3.hdf5']
>>>


2011/3/4 Grant Edwards <invalid at invalid.invalid>

> On 2011-03-04, Matt Funk <mafunk at nmsu.edu> wrote:
> > Hi Grant,
> > first of all sorry for the many typos in my previous email.
> >
> > To clarify, I have a python list full of file names called 'files'.
> > Every single filename has extension='.hdf' except for one file which has
> > an '.hdf5' extension. When i do (and yes, this is pasted):
> >         for filename in files:
> >             if (any(filename.endswith(x) for x in extensions)):
> >                 print filename
>
> I was unable to run that code:
>
> $ cat testit.py
>
> for filename in files:
>     if (any(filename.endswith(x) for x in extensions)):
>         print filename
>
> $ python testit.py
>
> Traceback (most recent call last):
>  File "testit.py", line 1, in <module>
>    for filename in files:
> NameError: name 'files' is not defined
>
> > However, it will print all the files in list 'files' (that is all
> > files with file extension '.hdf'). My question is why it doesn't just
> > print the filename with extensions '.hdf5'?
>
> Dunno.  You didn't provide enough information for us to answer your
> question: the code you posted won't run and don't tell us what values
> you're using for any of the variables.
>
> Here's a piece of runnable code that I think does what you want:
>
> $ cat testit.py
> files = ["foo.bar", "foo.baz", "foo.bax"]
> extensions = [".baz",".spam",".eggs"]
>
> for filename in files:
>     if (any(filename.endswith(x) for x in extensions)):
>         print filename
>
> $ python testit.py
> foo.baz
>
> --
> Grant
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110304/ad0363b1/attachment.html>


More information about the Python-list mailing list