MicroPython Skill Builders - #9 Strings

MicroPython Skill Builders - #9 Strings

Welcome to the nineth instalment of our MicroPython Skill Builders series by Tony Goodhew, aiming to improve your coding skills with MicroPython whilst introducing new components and coding techniques - using a Raspberry Pi Pico!

Today Tony will demonstrate how to create and manipulate strings in MicroPython.

What you will need

We assume that you have installed Thonny on your computer and set up your Raspberry Pi Pico with the most recent MicroPython firmware (UF2). If not, check out our Raspberry Pi Pico Getting Started Guide where this is covered in detail.

You will need:

What are strings?

Strings are a sequence of characters which are given a variable name and are manipulated in MicroPython in a similar manor to lists.

Here's a quick example of a simple string:

mystring = "I am a string"
Let's run an example program to show you some things we can do with strings. Open a new program in Thonny and paste in the following short program:
# A string is a sequence of characters 
ss = "ThePiHut.com" # A literal string definition

# Here the variable ss contains the sequence of characters between the quotation marks.
print()
print(ss)

# We can convert numbers into strings with function str(n).
fps = str(3.142) # Floating point number
ins = str(27)    # Integer or whole number

# Making longer stings from smaller strings by concatenation – comma separators 
ls = ss + "," + fps + "," + ins
print(ls)

# Obtain the number of characters ins a string with len(s)
length = len(ls)
print("\nLength of string:", length,"\n") # "\n" takes a new line

# Create string from ASCII numbers
t = chr(84)+chr(111)+chr(110)+chr(121)
print(t + "\n")

# Obtain ASCII character codes from string
for p in range(len(t)):
    print(t[p], ord(t[p])) # ord() converts a character to its ASCII value = opposite of chr()

This produces the following output in the Shell window:

ThePiHut.com
ThePiHut.com,3.142,27

Length of string: 21 

Tony

T 84
o 111
n 110
y 121

String Procedures & Functions

The code above the following procedures or functions:

string = str(number)  Converts a number to a string
n = int(string)  Converts a suitable string to an integer
n2 = float(string)  Converts a suitable string to a floating-point number
length = len(string)  Calculates the length of a string = number of characters
st = chr(ascii no)  Creates a string character from its AS
ascii_no = ord(character)  Calculates the ASCII code no from a given character string

Joining Strings

We can create a long string from other strings by joining them together, concatenating, using the + operator:

long_string = chr(84) + " Goodhew" + "\n”

In the example above, the last part \n is a new line character when printed. ASCII code 84 is a capital T.

Learn! ASCII stands for American Standard Code for Information Interchange and you can read about it here.

Splitting Strings (Substrings)

We often want to split up a long string into smaller pieces. There are several methods or instructions to help us with this task.

We use the syntax txt[start : end] where start and end are positions within the string (we can often leave one out and the appropriate end of the sting is assumed).

Run the code below then read on:

# Working with sub-strings

# Define some strings
txt = "Raspberry Pi Pico @ £3.95: a terrific board"
nos = "0123456789012345678901234567890123456789012 | Left to right" # Character counter
rev = "2109876543210987654321098765432109876543210 | Right to left" # Reverse character counter
nl = "\n"

# Print them out with one line of code
print(nos + nl + txt + nl + rev + nl)

# Find number of characters in a string
length = len(txt)
print("Length:",length)

#Find the position of a specific character in a string
a = txt.find("@")  # Where is the @ character
print("@ is at position:",a)

p = txt.find("£")  # Where is the £ character
print("£ is at position:",p)

c = txt.find(":")  # Where is the : character
print(": is at position:",c)

x = txt.find("%")
print("% is at position:",x,"NOT found")

# Extract the eleventh character from the string
ch = txt[10]
print("Eleventh character is:",ch) # Computers count from ZERO!

# Extract the cost of a Pico = positions: 20 to 24
sub = txt[p:c] # Extract characters from p to c-1
print(sub)

# Extract the first word
sp = txt.find(" ")
print("First word: " + txt[:sp])

# Extract last word, whch starts at position 38
print("Last word: " + txt[38:])
print("Last word: " + txt[-5:],"- Method 2") # Last 5 characters - count backwards 0 to 4!

The code above produces the following output:

0123456789012345678901234567890123456789012 | Left to right
Raspberry Pi Pico @ £3.95: a terrific board
2109876543210987654321098765432109876543210 | Right to left

Length: 43
@ is at position: 18
£ is at position: 20
: is at position: 25
% is at position: -1 NOT found
Eleventh character is: P
£3.95
First word: Raspberry
Last word: board
Last word: board - Method 2

Summary (Cheat Sheet)

Here's a little cheat sheet which may be useful to refer back to when writing your own code.

Note: You need to take great care with the position numbers, which are one more than you expect. Remember that the first character is at position 0.

length = len(txt)  # Length of string
c = txt.find(":")  # Where is the : character?  | -1 if not found
sub = txt[p:c]     # Extract characters from p to c-1
ch = txt[10]       # Extract the eleventh character – counting from zero
last5 = txt[-5:]   # Counting back from the far end with a negative number

Project - Extract individual words from a long string

Let's look at an example project where we want to extract individual words from a long string.

Run the code below then read on:

# Extract individual 'words' from a string to a list

txt = "Raspberry Pi Pico @ £3.95: a terrific board"
print(txt+"\n")    # Print the original string and new line
list = []

space =" "
while True:
    sp = txt.find(space)       # Is there a space character?

    if sp >= 0:                # We found a 'space' character
        extract = txt[0:sp]    # Extract the 'word' in front of the space
        print(extract)         # Print the 'word' extracted
        list.append(extract)   # Append the 'word' to the end of the list
        txt = txt[sp+1:]       # Remove the 'word' and the 'space' from txt
        print(txt+"\n")        # Print the shorter txt string
    else:
        list.append(txt)       # Append the remaining ‘word’
        break                  # Break out of loop

print("The list\n",list, "\n") # Print the list

print("The individual'words' from the list")
for i in range(len(list)):
    print("   ", list[i])

The code above provides the following output:

Raspberry Pi Pico @ £3.95: a terrific board

Raspberry
Pi Pico @ £3.95: a terrific board

Pi
Pico @ £3.95: a terrific board

Pico
@ £3.95: a terrific board

@
£3.95: a terrific board

£3.95:
a terrific board

a
terrific board

terrific
board

The list
 ['Raspberry', 'Pi', 'Pico', '@', '\xa33.95:', 'a', 'terrific', 'board'] 

The individual'words' from the list
    Raspberry
    Pi
    Pico
    @
    £3.95:
    a
    terrific
    board

Now try running the program with a different text string such as the very famous “The quick brown fox jumped over the lazy dog”.

The code is well commented so you should be able to follow the individual steps.

Some things to try

  • s = "1234,23.23,12,0.0045,9999,45,23" - Modify the last program to extract the numbers from this string and put them in a list. Print out the list and the average value of the numbers in the list.
  • Print the items in the list in reverse order
  • list = [15, 27, 45.76, -34.2, 108.7] - Convert the list of numbers to a string with the values separated by the "~", tilde, character. Print the string.

In the next Skill Builder tutorial, we will look at files and data logging.

About the Author

This article was written by Tony Goodhew. Tony is a retired teacher of computing who starting writing code back in 1968 when it was called programming - he started with FORTRAN IV on an IBM 1130! An active Raspberry Pi community member, his main interests now are coding in MicroPython, travelling and photography.

Featured Products

Raspberry Pi Pico - The Pi HutRaspberry Pi Pico - The Pi Hut
Raspberry PiRaspberry Pi Pico
Sale priceFrom £3.80 incl. VAT excl. VAT
Raspberry Pi Pico W - The Pi HutRaspberry Pi Pico W - The Pi Hut
Raspberry PiRaspberry Pi Pico W
Sale priceFrom £5.80 incl. VAT excl. VAT
Starter Kit for Raspberry Pi Pico (Includes Pico H) - The Pi HutStarter Kit for Raspberry Pi Pico (Includes Pico H) - The Pi Hut

Leave a comment

All comments are moderated before being published.

This site is protected by hCaptcha and the hCaptcha Privacy Policy and Terms of Service apply.