[Tutor] checking for substrings

Don Arnold Don Arnold" <darnold02@sprynet.com
Mon Dec 16 21:40:35 2002


----- Original Message -----
From: reavey
To: tutor@python.org ; reavey ; idiot1@netzero.net ; alan.gauld@bt.com
Sent: Monday, December 16, 2002 7:55 PM
Subject: [Tutor] checking for substrings


Sirs:

I'm confused?
>>>"the rain in spain falls mainly on the plain"
>>> "falls " in "the rain in spain falls mainly on the plain"
1
         #"in" looks like a yes or no test.#


Well, I'm confused too, because I get:

>>> 'falls' in 'the rain in spain falls mainly on the plain'
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in ?
    'falls' in 'the rain in spain falls mainly on the plain'
TypeError: 'in <string>' requires character as left operand

This is under 2.2.1 on WinXP. What version of Python are you running?


>>>a = "the rain in spain falls mainly on  the plain"
>>> "falls" in a.split()
1
>>>print a.find("falls")
18
>>>a.find("falls")
18
>>>b = "the rain in spain falls mainly on the plain in june"
Is there a way to use find to "see" the second "in" in the above example?


Yes. find() can actually take three arguments: the string your searching
for, the starting offset for your search (defaults to zero), and the ending
offset (defaults to the length of the string you're searching). So you can
supply find()'s starting offset and increment it in a loop until you run out
of matches:

>>> startPosition = 0
>>> mystring = 'the rain in spain falls mainly on the plain'
>>> while 1:
            startPosition = mystring.find('in',startPosition)
            if startPosition == -1:
              break
           else:
              print 'found at:', startPosition
              startPosition += 1

found at: 6
found at: 9
found at: 15
found at: 26
found at: 41


A reverse find?


That's what rfind() is for:

>>> 'the rain in spain falls mainly in the plain'.rfind('in')
41


TIA
Re-v


HTH,

Don