feature request: a better str.endswith
John Machin
sjmachin at lexicon.net
Fri Jul 18 20:02:28 EDT 2003
More information about the Python-list mailing list
Fri Jul 18 20:02:28 EDT 2003
- Previous message (by thread): feature request: a better str.endswith
- Next message (by thread): feature request: a better str.endswith
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
mis6 at pitt.edu (Michele Simionato) wrote in message news:<2259b0e2.0307180401.5dae02f2 at posting.google.com>... > 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" > alternative 1: >>> import re >>> has_image_file_extn = re.compile(r".*[.](jpg|jpeg|png|gif)$").match >>> has_image_file_extn('foo.jpg') <_sre.SRE_Match object at 0x00769F30> >>> has_image_file_extn('foo.txt') >>> The above has factored out the common "." but is otherwise general for any list of suffixes. alternative 2: >>> has_image_file_extn = lambda f: f.split('.')[-1] in ['jpg','jpeg','png','gif'] >>> has_image_file_extn('foo.jpg') 1 >>> has_image_file_extn('foo.txt') 0 >>> This is of course restricted to cases where you can isolate the suffix lexically. If the list is long and/or used frequently, then it might be better to use a built-at-module-start-up dictionary instead.
- Previous message (by thread): feature request: a better str.endswith
- Next message (by thread): feature request: a better str.endswith
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list