M
Michele Simionato
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.
Any reaction, comment ?
Michele
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.
Any reaction, comment ?
Michele