Searching in Text
You know in from lists: "Tom" in guests is True if one of the elements is exactly "Tom". With text, in does more: it checks whether one text is a part of another, anywhere in it.
print("cat" in "concatenate")
print("dog" in "concatenate")
print("An" in ["Anna", "Tom"])
print("An" in "Anna")This prints:
True
False
False
TrueLook at the last two lines. In a list, in looks for a whole element, and no element is "An". In a text, it looks for a part, so it finds "An" at the start of "Anna".
That's how a search box works: it shows the titles that contain what you typed. A search usually doesn't care about case, so each title is turned into lowercase first:
songs = ["Night Drive", "Summer Nights", "Rainy Day", "Midnight Train"]
search = "night"
for song in songs:
if search in song.lower():
print(song)This prints:
Night Drive
Summer Nights
Midnight TrainWhen you need to know where the part is, use the method find(). It returns the index at which the part starts the first time it appears, or -1 if it isn't in the text at all. And the method count() returns how many times the part appears:
sentence = "The cat sat on the mat."
print(sentence.find("cat"))
print(sentence.find("dog"))
print(sentence.count("at"))
print(sentence.count("the"))This prints:
4
-1
3
1"cat" starts at index 4: T is at index 0, and the space at index 3 is a character too. "at" is in the sentence three times, in cat, sat and mat: count() counts parts of the text, not words. And "the" is there only once, because The at the start has a capital T. Like ==, in, find() and count() care about case.
Why -1 and not 0? Index 0 is the start of the text, so 0 means “found right at the start”. When you only need to know whether a part is there, use in: it's simpler than checking find() for -1.
Instructions
- 1
Social networks don't care about case in hashtags:
#Pythonand#pythonare the same tag. Write anifstatement that checks whetherpostcontainstag, in any case, and printsFound: #python. Otherwise, it printsNot found: #python. Take the tag fromtagin both, for example in an f-string, and keep the linetag = "#python": the exercise also tries other tags in it. - 2
Below, print how many hashtags the post has, that is, how many times
#appears in it:Hashtags: 3.