Python: More Fun with Strings - Putting Our Strings to the Test (Page 4 of 5 )
Sometimes it is necessary to test the data in a string. Maybe we want to know if it contains a specific letter or word or sentence, or any text at all. We can perform a true/false boolean test like so:
>>> cartoon='The Smurfs rock.'
>>> 'snork' in cartoon
False
>>> 'smurf' in cartoon
False
>>> 'smurfs' in cartoon
False
>>> 'Smurfs' in cartoon
True
>>> 'Smurf' in cartoon
True
>>> 'rock' in cartoon
True
>>> 'The Smurfs' in cartoon
True
>>> 'The Smurfs suck' in cartoon
False
>>> 'The Smurfs rock' in cartoon
True
In the above example we assign the value "The Smurfs rock." to the variable cartoon. We then run a number of tests to see if certain words and eventually sentences appear in the cartoon variable. You will note that the method is case sensitive (it won't find 'smurfs' but it will find 'Smurfs').
You can also use "not in," to see if text is not in the string, like this:
>>> 'Snorks' not in cartoon
True
Another method of testing whether some text is in a string is to use the find() method, which returns the position of the text in the string:
>>> cartoon.find('Smurfs')
4
>>> cartoon.find('rock')
11
>>> cartoon.find('boo')
-1
As you can see, the word 'Smurfs' begins at the fourth character, and 'rock' begins at the eleventh character (spaces count as one character). Since the text 'boo' is not in our string, the program returns the value -1.
Next: Converting Data and Sorting >>
More Python Articles
More By James Payne