feature request: a better str.endswith
Bob Gailer
bgailer at alum.rpi.edu
Fri Jul 18 19:05:06 EDT 2003
At 05:01 AM 7/18/2003 -0700, 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.
>
>Any reaction, comment ?
One of my favorite languages is APL. All APL variables are arrays of 0 or
more dimensions, and most of the operations in APL take arrays as arguments
and return arrays as results. So I am often frustrated in Python when I
have to write a construct such as your example, when, IMHO, it would be
easy to extend Python to accept sequences as arguments where only single
values are currently allowed. One example is providing a sequence of
integers to index another sequence, vis. given seq = [3, 5, 7, 1 ,4],
seq[(1,3, 0)] would produce [5, 1, 3]. Currently the tersest way to do this
is [seq[x] for x in (1,3,0)]. The new extension would probably execute
faster, and is more readable. There are probably more situations that could
also benefit from such an extension. I know that I can create some of these
using magic methods, but how much nicer if they were native.
In APL one can specify indexes for the various dimensions of an array. If B
is a rank 2 array, B[1 2;3 4] retrieves columns 3 and 4 of rows 1 and 2.
WIBNI one could in a similar way drill into a nested list. I know the
various importable array modules do some of these tings, but they are
limited to homogeneous data.
Bob Gailer
bgailer at alum.rpi.edu
303 442 2625
-------------- next part --------------
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003
More information about the Python-list
mailing list