Characters Inside Strings

Each string is a sequence of characters, where each character is defined by a code number.  For example, the string "ABC 123" is stored as a sequence of numbers: 65 65 66 67 32 49 50 51 66 49 50 51.  These numbers are called ASCII codes.  ASCII stands for American Standard Code for Information Exchange.  

  • Open the ASCII chart at this link.
  • Find the Dec ASCII codes for upper-case A, B, and Z.   
  • Find the Dec ASCII codes for lower-case a through z.
  • Find the Dec ASCII codes for digits.

You can use Python statements to return the ASCII code of a character, and also to return the character for a given ASCII code.  Let's try that!

Example script: chars_in_strings_intro

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

from microbit import *

sleep(1000)

print("n = ASCII code for A")
n = ord("A")
print("n =", n)
print()
 
print("c = character with ASCII code 66")
c = chr(66)
print("c =", c)
print()
  • Open the terminal.
  • Verify that it displays a message that the ASCII code for A is 65, and the character with the ASCII code 66 is B.
  • Try some of your own characters and ASCII codes.


How chars_in_strings_intro Works

The statement print("n = ASCII code for A") displays a heading to help give context to the messages below it.  

print("n = ASCII code for A")

The function ord() returns the ASCII code of a string that contains a single character.  The ASCII code for the character A is 65.  So, ord("A") returns 65, and n = ord("A") stores the value 65 in the variable n.  

n = ord("A")

After that, print("n = ", n) displays "n =", followed by the value of n, which is 65.  Lastly, the print() just prints an empty line.

print("n =", n)
print()

Note: the ord() function only works if the string contains a single character!   The MicroPython runtime doesn't care whether you enclose characters in single or double-quotes, but single quotes for single characters are more readable.  Consider "A" vs. 'A'.

After that empty line, print("c = character with ASCII code 66") prints another heading.  

print("c = character with ASCII code 66")

The chr() function accepts an ASCII code, and returns that ASCII code's character.  So, c = chr(66) stores the character B in a variable named c.  

c = chr(66)

Since c now stores the character B, print("c =", c) prints c = B.

print("c =", c)
print()