[Tutor] Slicing Question

Jeff Shannon jeff@ccvcorp.com
Wed Apr 9 13:06:02 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? 

You can do it all with one slicing operation, by specifying a start 
point as well as an end point.

if fileName[-9:-5].lower() == "test":

You can also use some of the features of the os.path module, which are 
designed for handling filenames, to allow you to write something that'll 
be more flexible.  We can throw in a string method as well:

import os
base, ext = os.path.splitext(fileName)
if base.endswith("test"):

This doesn't require knowing anything about the extension that we're 
stripping off, nor does it require figuring out how long "test" is, so 
it'd be easier to check for an arbitrary string there (perhaps 
determined elsewhere in your program).

Jeff Shannon
Credit International