String handling

Length, indexing, slicing, searching and joining strings, and f-strings.

F3.1Strings, lists and recordsGCSE15 min

Do this lesson in the simulator

Text in a program is a string: a string of characters, in order. Robots report what they are doing in strings, users type strings, and messages between robots are strings. This lesson is about taking strings apart and putting them together.

Joining strings

+ on strings joins them, which is called concatenation:

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

first = "Bug"
second = "Bot"
whole = first + second
print(whole)
print("Hello, " + whole + "!")
print("-" * 20)

Run this in the simulator

Joining does not add spaces; you add them yourself, inside the quotes. * repeats a string, which is handy for a line of dashes.

A string and a number cannot be joined with +. str() from lesson F1.8 turns the number into text first:

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

print("battery: " + str(battery()) + "%")

Run this in the simulator

Length and indexing

len counts the characters. Each character has a position, its index, counting from 0:

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

word = "BugBot"
print(len(word))
print(word[0])     # the first character
print(word[3])     # the fourth
print(word[-1])    # the last: negative indexes count from the end

Run this in the simulator

B u g B o t
0 1 2 3 4 5

The last index is always one less than the length. word[6] would be an IndexError: there is no seventh character.

Slicing

A slice takes part of a string: from one index up to, but not including, another:

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

word = "BugBot"
print(word[0:3])   # Bug
print(word[3:6])   # Bot
print(word[:3])    # from the start
print(word[3:])    # to the end

Run this in the simulator

The stop number is not included, the same rule as range. word[0:3] is three characters: indexes 0, 1 and 2.

Searching

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

message = "wall ahead at 30 cm"
print("wall" in message)         # True or False
print(message.find("ahead"))     # the index where it starts
print(message.find("ball"))      # -1 means not found
print(message.upper())
print(message.replace("wall", "box"))

Run this in the simulator

in asks whether one string is inside another. find tells you where, or -1 if it is not there. upper, lower and replace give back a new string; the original is unchanged.

Building reports with f-strings

The neatest way to build a line of text from values is an f-string: an f before the opening quote, and anything inside { } is worked out and dropped into the text:

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

forward(50, distance=15)
x, y = position()
print(f"BugBot at x={x} y={y}")
print(f"wall in {distance()} cm, battery {battery()}%")
print(f"a third: {10 / 3:.2f}")

Run this in the simulator

:.2f inside the braces shows two decimal places. No str() needed: the f-string converts the numbers itself.

Task: status report

Drive 10 cm, then print one line in exactly this shape (your numbers will differ):

BugBot at x=0.0 y=10.4, wall in 29.6 cm, battery 92%
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

forward(50, distance=10)
x, y = position()
print(f"BugBot at x={x} ...")

Task: name tag

Ask Name?, then print three lines: the name in capitals, its first and last letters as first A, last A, and 3 letters with the right number. Then beep once for every letter. The task answers Ada; make it work for any name.

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

name = input("Name? ")

Challenges

  1. Print a name backwards. (Hint: a slice can have a third number, the step, and -1 walks backwards.)
  2. Ask for a sentence and print how many times the letter e appears in it, using count.
  3. Print a report with the heading rounded to a whole number, framed by lines of =.