Programs that Hold Many Values

Text inside a program

Work out how many characters a piece of text holds, which character sits at a given position, and what joining two pieces of text end to end gives.

A program can hold text as well as numbers. Text is written between quote marks and is called a string, and the quote marks are how the program tells where the text begins and ends — they are not part of the text itself. Three of the things you already do to a list work on a string too, and mean almost the same thing. The word len gives how many characters there are. Square brackets read one character out by its position. And a loop can go through it a character at a time.

Positions count from nought here too, and a space is a character

A string is a run of characters in a fixed order, so everything about positions carries straight over from lists: the first character is at position 0, the last is at one less than the length, and asking for the length itself as a position goes past the end. Two things are new. A space is a character like any other and is counted like any other, which is where most wrong answers about length come from. And the plus sign does two different jobs: between two numbers it adds them, and between two pieces of text it joins them end to end, putting nothing at all in between.

Worked example

What does this program print?

word = "monitor"
print(len(word))
print(word[0] + word[6])
  1. Number the characters before anything else: m is at 0, o at 1, n at 2, i at 3, t at 4, o at 5, r at 6.

    Seven characters, numbered 0 to 6. Writing them out with their numbers underneath takes a moment and saves every off-by-one there is.

Try it together

Now two pieces of text, measured separately and then measured joined.

first = "note"
second = "book"
print(len(first) + len(second))
print(len(first + second))

The two lines look alike and are not. Take the brackets apart carefully.

    1.How many characters are in the first piece of text on its own?

    Have a go

    Have a go on your own. What does this program print?

    word = "cursor"
    print(word[2])

    Ready to practice?

    Eight questions on what you have just read. Nothing is timed, and you can play as many times as you like.

    Print a worksheet