[Tutor] if statement [the string methods: endswith(), startswith(), and find()]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 30 Jul 2002 15:18:59 -0700 (PDT)


On Tue, 30 Jul 2002, Sean 'Shaleh' Perry wrote:

>
> On 30-Jul-2002 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()


This almost works.  What we can ask is if the filename ends with the
extension ".jpg":

###
>>> 'foo.jpg'.endswith('.jpg')
1
>>> 'foo.jpg'.endswith('.png')
0
###

We want to check that the filename ends with that suffix '.jpg', and not
just if the filename contains the string '.jpg'.  We need to be strict
about this, because otherwise, we can hit pathological file names like
'foo.jpg.backup'!


But although we end up being safer with endswith(), we should say that
os.path.splitext() is an even better way to grab at the file extension,
since it takes platform-specific details into account.  Still, it's nice
to know that 'endswith()' is a method we can use to search the end of a
string.  Symmetrically, strings also have a 'startswith()' method to look
at the beginning of a string.


If we only care if a particular substring appears anywhere, we can use the
find() method to see where exactly some substring is located: if we can't
find the darn string, then find() will return us the nonsense index number
'-1':

###
>>> 'supercalifragilisticexpialidocous'.find('frag')
9
>>> 'supercalifragilisticexpialidocous'.find('foo')
-1
###


Hope this helps!