Testing the content of strings

Python lets you test whether strings have certain content. These tests return True or False (Boolean results).

To test whether text is anywhere in a string, type the text you're searching for in quotation marks, followed by in and the name of the string. This example gives a name to a string and tests for the string 'goose' inside the string.


To test whether text is not in the string, use not in rather than in.

Tip Python 2.2 and earlier don't have the in keyword. In those versions, you can test for text in a string by using the find() or count() method.

To test whether text is at the end of a string, use the endswith() method, as shown here. (The startswith() method works the same way but finds text at the beginning of a string.)

Was this article helpful?

0 0

Post a comment