feature request: a better str.endswith
Thomas Güttler
guettler at thomas-guettler.de
Fri Jul 18 08:59:30 EDT 2003
Michele Simionato wrote:
> I often feel the need to extend the string method ".endswith" to tuple
> arguments, in such a way to automatically check for multiple endings.
> For instance, here is a typical use case:
>
> if filename.endswith(('.jpg','.jpeg','.gif','.png')):
> print "This is a valid image file"
>
> Currently this is not valid Python and I must use the ugly
>
> if filename.endswith('.jpg') or filename.endswith('.jpeg') \
> or filename.endswith('.gif') or filename.endswith('.png'):
> print "This is a valid image file"
>
> Of course a direct implementation is quite easy:
>
> import sys
>
> class Str(str):
> def endswith(self,suffix,start=0,end=sys.maxint):#not sure about
> sys.maxint
> endswith=super(Str,self).endswith
> if isinstance(suffix,tuple):
> return sum([endswith(s,start,end) for s in suffix]) # multi-or
> return endswith(suffix,start,end)
>
> if Str(filename).endswith(('.jpg','.jpeg','.gif','.png')):
> print "This is a valid image file"
>
> nevertheless I think this kind of checking is quite common and it would be
> worth to have it in standard Python.
Hi,
I like this feature request.
if the argument to endswith is not a string,
it should try to treat the argument as a list or tuple.
thomas
More information about the Python-list
mailing list