Searching in a string
Often a program needs to know whether a string contains some piece of text. The in operator tells: part in text is True when part appears somewhere in text, and False when it doesn't.
text = "strawberry"
print("straw" in text)
print("berry" in text)
print("Berry" in text)
print("w" in text)
True
True
False
TrueCapitals count: "Berry" with a capital B isn't in "strawberry". And not in is the opposite: "x" not in text is True. Since both give True or False, they fit right into an if or a while:
message = input("Message: ")
if "!" in message:
print("Sounds exciting")
if "?" not in message:
print("No questions asked")
Pizza tonight!Message: Pizza tonight!
Sounds exciting
No questions askedWhere is it? find
in says whether a piece is in a string, but not where. For that, a string has find: text.find(part) gives the index where part first starts, or -1 if it isn't there at all.
text = "strawberry"
print(text.find("berry"))
print(text.find("r"))
print(text.find("kiwi"))
5
2
-1There are three rs in strawberry; find gives the first one, at the index 2.
find is written in a new way: after the string, with a dot. A function that belongs to a value like this is called a method. find is a method of strings, and text.find("r") searches the string text, the one in front of the dot. Compare len(text), a function, where the string goes inside the parentheses. Strings have many more methods, and you'll meet them soon.
An index and a slice together
The index from find goes well with a slice. This program splits a file name at its dot:
file_name = input("File: ")
dot = file_name.find(".")
if dot >= 0:
print("Name: " + file_name[:dot])
print("Type: " + file_name[dot + 1:])
else:
print("No dot in the name")
notes.txtFile: notes.txt
Name: notes
Type: txtCheck for -1 before you use the index. Without the check, a name with no dot would give -1, and file_name[:-1] would quietly cut off the last character instead of failing.