Numbers get most of the attention in maths, but programs spend a lot of time with words: names, messages, passwords, chat, game dialogue. In Python, a piece of text is called a string, because it is a string of characters lined up in order.
Making strings
Put text inside quote marks. Single or double quotes both work, as long as you match them:
name = "Maya"
greeting = 'Hello'Joining strings together
You can stick strings together with +. Programmers call this concatenation, which is a wonderful word to say out loud.
first = "Maya"
message = "Hello, " + first + "!"
print(message)Notice the space inside "Hello, ". Python only puts in the spaces you ask for.
A tidier way is an f-string, which drops variables straight into the text:
age = 9
print(f"{first} is {age} years old.")The f before the quote and the curly brackets { } do the magic.
Useful string tricks
Strings come with built-in abilities called methods:
word = "banana"
print(word.upper())
print(word.title())
print(len(word))
print(word.count("a"))
print(word.replace("a", "o"))That prints BANANA, Banana, 6, 3 and bonono. Let your child guess each result before running it. Guessing, then checking, is one of the best habits in programming.
Picking out letters
Just like lists, strings have positions that start at 0:
print(word[0])
print(word[-1])The first prints b, and -1 counts from the end, so the second prints a. You can also take a slice:
print(word[0:3])This prints ban: from position 0 up to, but not including, position 3.
Numbers versus text
A common surprise: "5" and 5 are different. The first is text, the second is a number.
print("5" + "5")
print(5 + 5)The first prints 55 (joined), the second prints 10 (added). This matters when you use input(), because whatever the user types arrives as text. To do maths with it, convert it with int():
age = int(input("How old are you? "))
print("Next year you will be", age + 1)Try these challenges
- Ask for a name and print it in capital letters.
- Ask for a word and print how many letters it has.
- Ask for a sentence and replace every space with a dash.
- Print the first and last letter of any word.
- Build a silly "story maker" that asks for a name, an animal and a food, then prints a short story using an f-string.
Why it matters
Strings are the gateway to chat bots, quizzes, word games and secret codes. Pair this with if statements and your child can write a simple password checker or a guessing game. The Python course has hands-on practice with text from the very first lessons.