Try This: Find the Substring

Sometimes it's wise to check if a string contains a certain phrase.  For example, a micro:bit might be sending radio commands to more than one cyber:bot robot.  A unique name could be used to select which cyber:bot in the group should execute the command.  

The string.find() method can help with this.  It returns the index of the first character in the matching substring.  If it returns 0, it means it found the character at the very beginning of the string.  If it returns 5, it means it started at the fifth character in the string.  If it doesn't find a match, it returns -1.  

Here are some examples of how string.find() can be used:

  • n = s.find("run") finds the first instance of "run" in a string named s and stores it in n.
  • s.find("run", 10, 20) finds the first instance of "run" between the 10th and 19th character —in Python, the beginning argument (10) is included, but the ending argument (20) is excluded.
  • s.find("run", 10) looks "run" from the 10th character to the end

Keep in mind, you can also search for characters.  Just use a single character in the search, like s.find("A").

As mentioned in the Strings and Characters page, string objects also have useful methods.  Here are a few examples to try:

new_string = string.replace("substring", "replacemnt_string")
lower_case = string.lower()
upper_case = string.upper()
new_list = string.split()

Here we have three examples of searching for substrings with string.find().  After finding the index of the first and second instances of one substring, it looks for a substring that isn't there.  Examine the searches and results carefully.  

Example script: comp_find_check_try_this

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

from microbit import *

sleep(1000)

s = "Arthur: It is 'Arthur', King of the Britons."

n1 = s.find("Arthur")
n2 = s.find("Arthur", 7, len(s))
n3 = s.find("Lancelot")

print("Results of string.find():")
print("n1 = ", n1, ", n2 =", n2, ", n3 = ", n3)
  • Open the terminal.
  • Verify that the results are 0, 15, and -1.

Does this make sense?  The first instance of "Arthur" starts at character 0 in s.  The second starts at 15.  Since Lancelot isn't in there, it returns -1.