Your Turn: Exact Match vs Found in String

Sometimes a script has to make the distinction between an exact match and the presence or absence of a term in a string.  Even if string.find() returns 0, that doesn't prove that there aren't more characters following the match.  One way to solve this is to use the is equal to == operator to check if the string is an exact match.  If it isn't, then use the string.find() method to check if the substring is anywhere in the string.

Example script: comp_find_check_your_turn

  • Enter this script and save it as comp_find_check_your_turn.  
  • Flash the script into the micro:bit.
# comp_find_check_your_turn

from microbit import *


while True:
    s = input("Type run: ")
    n = s.find("run")
    if(s == "run"):
        print("Good, you typed run.")
    elif(n != -1):
        print("It contains run.")
        print("r is the", n, "th character.")
        print("You didn't type run.")       
  • Open the terminal.
  • Try entering each of these inputs:
    I like to run
    I like to walk
  • Verify that the script can recognize the difference between these three inputs.