Python Arena
Step 6 of 6

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)
Output
True
True
False
True

Capitals 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")
Input
Pizza tonight!
Output
Message: Pizza tonight!
Sounds exciting
No questions asked

Where 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"))
Output
5
2
-1

There 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")
Input
notes.txt
Output
File: notes.txt
Name: notes
Type: txt

Check 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.

Your task

Challenge 1 of 3

Fill in the blank so the program says whether the text typed in has an @ in it.

Email: ada@example.com
Looks like an email address

Challenge 2

Write a program that asks for a message and prints Spam! if the message contains the word free or the word winner, and Looks fine otherwise. Look for the words in small letters only.

Message: you are a winner
Spam!

Challenge 3

Write a program that asks for an email address and prints its user name (the part before the @) and its domain (the part after the @). If there's no @ at all, it prints Not an email address.

Email: ada@example.com
User: ada
Domain: example.com