[Tutor] Slicing Question

Jay Dorsey python@jaydorsey.com
Wed Apr 9 13:18:07 2003


Brian Christopher Robinson wrote:
> I wrote this line of code today:
> 
> if fileName[:-5][-4:].lower() == "test":
> 
> What it does it take a file name that I already know ends in ".java", 
> cut off the ".java" part, and see if the last 4 letters are test.  I was 
> wondering if there's a simpler way of doing this?
> 

How about slicing it like this:

 >>> if fileName[-9:-5].lower() == "test":
...     print "there it is"
...
there it is

Alternatively, you could use a regular expression

 >>> x = "blahblahtest.java"
 >>> import re
 >>> reFilename = re.compile(".+test.java", re.I)
 >>> if reFilename.search(x):
...     print "there it is"
...
there it is




-- 
Jay Dorsey
python at jay dorsey dot com