[Tutor] if statement

Jeff Shannon jeff@ccvcorp.com
Tue, 30 Jul 2002 11:11:15 -0700


"Kelly, Phelim" wrote:

> Hi,
>         hoping you can help me.... I'm trying to create an if statement that
> works if a certain string contains a specified 4 characters. Basically I
> want to quit the program if an imported file is a .jpg file, so I'm looking
> for an if statement kind of like:
>
> if filename contains ".jpg":        (I'm looking for correct syntax for this
> bit)
>    sys.exit()

Well, there's a couple of ways to do this.  You can simply look at the last bit of the string, in a couple of different ways:

# using a string method
if filename.endswith(".jpg"):    ...

# using slice notation
if filename[-4:] == ".jpg":    ...

However, since you're specifically working with filenames, I'd recommend looking into the os.path module.

>>> import os
>>> filename = "c:\\MyProgram\\Lib\\image.jpg"
>>> os.path.splitext(filename)
('c:\\MyProgram\\Lib\\image', '.jpg')
>>> name, ext = os.path.splitext(filename)
>>> if ext == '.jpg':
...     print "yes!"
...
yes!
>>>

There is, however, one slight problem to watch for, however you do this.

>>> filename = "IMAGE.JPG"
>>> name, ext = os.path.splitext(filename)
>>> if ext == '.jpg':
...     print "yes!"
>>>

Note that our test failed, because the case was different.  The simple thing to do, here, is to use the string method lower(), to make everything lowercase:

>>> if ext.lower() == '.jpg':
...     print "yes!"
...
yes!
>>>

Hope that this helps...

Jeff Shannon
Technician/Programmer
Credit International