Try This: Check String Length

If your script uses an index that's larger than the string, it'll cause an exception.  To find out how many characters are in a string, Python has that built-in function called len() that returns the number of characters in a string.  Your script can check a string's length, then can then use that result in indexing when accessing characters in that string, so that it never tries to access an out of bounds character.  This is especially important when each character is indexed in a loop.

Before indexing all the characters in a string, let's use len() to verify that there are 12 characters in the string.

Example script: char_access_try_this

  • Enter, name, and save char_access_try_this.  
  • Click the Send to micro:bit button.
# char_access_try_this

from microbit import *

sleep(1000)

s = "ABCDEF 12345"
 
print("Characters in s:")

length = len(s)

print("length =", length)

print()
  • Check the results in the serial monitor.
  • Verify that it displays length = 12.