← Back to course
Code Crew G4 / Week 05 / Thursday
4/6
Week 05 Β· Strings up close

Thursday

Is it in there?
// Letter by letter
⏱ about 15 min

Thursday: Is it in there?

The station sends hundreds of short status messages every day. Raven wants an alert whenever a message mentions low supplies. Rocket starts reading them one by one.

"Water ok. Air ok. Fuel low on deck 3." He rubs his eyes. "There are so many!"

Raven asks, "What do you notice about the messages we care about? They all have the same little word inside." Nova blinks. "Would you like a hint? Python can check if one string is hiding inside another."

in finds a string inside a string

in checks whether one string is inside another. It gives True or False.

in cares about capitals. "Fuel" and "fuel" are different.

log = "fuel low on deck 3"
print("low" in log)
print("high" in log)
print("Fuel" in log)
if "deck" in log:
    print("Deck alert!")
The screen shows
True
False
False
Deck alert!
CheckDoes Python say True?
"air" in "air ok"?
"ok" in "Book"?
"OK" in "air ok"?
"tape" in "tap"?
WHY THIS EXERCISEin finds letters anywhere, even inside a bigger word like Book.

in inside a loop

msgs = ["water ok", "fuel low", "air ok", "tape low"]
for m in msgs:
    if "low" in m:
        print("Check:", m)
The screen shows
Check: fuel low
Check: tape low
msgs = ["Hatch open", "hatch closed", "Lamp on", "Hatch closed"]
count = 0
for m in msgs:
    if "Hatch" in m:
        count = count + 1
print(count)
What number does the program above show?
WHY THIS EXERCISESearching with in is case sensitive. Programs often use lower first to avoid surprises.
FIX THE SEARCH
  • Read the question.
  • Tap your answer.
Rocket wants to count every hatch message, big H or small h. Which if line does that?
Try it
Pick a short word, like an.
Find three bigger words that have it inside.

Practice lab: alert or fine?

msgs = ["air ok", "Air low", "water low", "lamp ok"]
for m in msgs:
    if "low" in m:
        print("Alert:", m)
    else:
        print("Fine:", m)
How many lines start with Alert?
How many times does the loop run?
What does "air" in "Air low" give?
SEARCH CHECK
  • Read the question.
  • Tap your answer.
What does "ok" in "lamp ok" give?
What does "Ok" in "lamp ok" give?
Which check finds air with a big A or a small a?
CheckDoes Python say True?
"star" in "starlight"?
"light" in "Starlight"?
"Star" in "starlight"?
"rats" in "star"?
WHY THIS EXERCISEin matches exact letters in order. Backward letters do not count.
A loop checks "an" in m for each m in ["fan", "band", "pin", "Ant"]. How many times is it True?
WHY THIS EXERCISEfan and band have an inside. Ant has An, which is different.

Great searching! Tomorrow you will mix slices, upper and loops to make crew tags.

← Wednesday