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, name, and save comp_find_check_your_turn.  
  • Click the Send to micro:bit button.
# comp_find_check_your_turn

from microbit import *

sleep(1000)

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.")
    else:
        print("You didn't type run.")       
  • Check the results in the serial monitor.
  • Try entering each of these inputs:
    run
    I like to run
    I like to walk
  • Verify that the script can recognize the difference between these three inputs.