Loops, and where your data lives

INPUT · Slides

Searching inside a string

01 / 07

Asking whether it is in there

To take something out by number you have to know where it is. Start with the simpler question: is it even in there?

The tool is in, the same word you used on lists. The answer comes back as True or False.

text = "heavy rain today"print("rain" in text)print("snow" in text)

Result

True
False

02 / 07

Put it together with if

Since it comes back as True or False, you can write it straight into an if.

"If it contains this, do that" is now something you can express.

text = "heavy rain today"if "rain" in text:    print("take an umbrella")

Result

take an umbrella

03 / 07

Asking where it starts

When you want the place as well, you use find. The number where it was found comes back.

The writing is text.find("rain") — a . on the end of the string you are searching. The same shape as append on a list.

text = "heavy rain today"print(text.find("rain"))

Result

6

04 / 07

Not found gives -1

find does not error when it finds nothing. It returns -1 instead.

Since a real position is never below zero, an impossible number is how it says "not there".

0 coming back means "it was right at the front", -1 means "it was not there at all". Take care not to read one for the other.

text = "heavy rain today"print(text.find("snow"))print(text.find("heavy"))

Result

-1
0

05 / 07

Counting how many

count tells you how many times something turns up.

If there are none at all you get 0. This one never goes to -1.

word = "banana"print(word.count("a"))print(word.count("x"))

Result

3
0

06 / 07

Looking only at the ends

There are tools just for "does it begin with" and "does it end with".

  • startswith … does it begin with that string
  • endswith … does it end with that string

Both answer True or False. You could slice and compare instead, but these say what they mean as you read them.

text = "heavy rain today"print(text.startswith("heavy"))print(text.endswith("tomorrow"))

Result

True
False

07 / 07

Search, then cut

A number from find goes straight into a slice. The searching tools and the cutting tools are a pair.

The example below takes "from just after the : to the end". You can cut it out without knowing where the separator sits.

Next lesson is about the tools that work on a string.

line = "name:Yui"i = line.find(":")print(line[i + 1:])

Result

Yui