Python String find(), count() and startswith(): Search Text
Searching a string means asking where text appears, how often, or whether a string starts or ends with it, using find(), count(), startswith() and endswith().
Read String Methods first. This lesson also uses if, elif, else and Membership Testing.
Find where text appears
.find(text) gives the index where text first starts.
sentence = "the cat sat on the mat"
print(sentence.find("cat"))
print(sentence.find("dog"))
"cat" starts at index 4. "dog" is not there, so .find() gives -1.
find() or in?
Use in when you only need yes or no. Use .find() when you need the
position. The trap: -1 is not "false", so don't use .find() alone as a
condition.
sentence = "cat nap"
if sentence.find("cat"):
print("found with find")
else:
print("find gave 0, which counts as false")
if "cat" in sentence:
print("found with in")
"cat" is at index 0, and 0 counts as false. Check != -1 instead, or use in.
Count matches
.count(text) says how many times text appears, without overlaps.
sentence = "the cat sat on the mat"
print(sentence.count("at"))
print(sentence.count("the"))
print("aaaa".count("aa"))
"aaaa".count("aa") is 2, not 3: once a match is counted, the search
continues after it.
Check the start or end
.startswith() and .endswith() give True or False.
filename = "scores.txt"
print(filename.endswith(".txt"))
print(filename.startswith("Scores"))
The second line is False: every search here is case-sensitive. Lowercase
both strings first when case should not matter.
Note: These methods match exact text only. They can't match patterns such as "any digit". For patterns, see regular expressions.
See also: Regular expressions, Chaining string methods.
Your turn
For each word in words, print the word, where "an" first appears in it, and
how many times "an" appears. Skip words that end with "s", using
if not word.endswith("s"):.
words = ["banana", "plans", "cherry", "mango"]
# add your code: loop over words; for words not ending in "s", print word, find("an") and count("an")
Expected output
banana 1 2
cherry -1 0
mango 1 1