← All lessons
Python basics · Lesson 4 of 10

Working with text

Strings are everywhere in programs: names, messages, file contents, web pages. Python gives you plenty of ways to work with them.

+ joins two strings into one (this is called concatenation), and * repeats a string. Note that + adds no space; put one in yourself.

first = "Ada"
last = "Lovelace"
print(first + " " + last)
print("ho" * 3)
Prints
Ada Lovelace
hohoho

len() is a function that tells you the length of a string: how many characters it has. A character is one letter, digit, space or symbol.

print(len("Python"))
print(len("hi there"))
Prints
6
8

Each character has a position number called its index. Indexes start at 0, not 1, which takes a little getting used to. Put the index in square brackets after the string to get that character. Negative indexes count from the end: -1 is the last character.

word = "duck"
print(word[0])
print(word[2])
print(word[-1])
Prints
d
c
k

Some functions belong to a value and are written after it with a dot. These are called methods. Strings have dozens. upper() and lower() change the case, and replace(old, new) swaps one piece of text for another. A method gives back a new string; the original isn't changed.

shout = "quack"
print(shout.upper())
print("Hello World".lower())
print("I like cats".replace("cats", "ducks"))
Prints
QUACK
hello world
I like ducks

The neatest way to build a message from variables is an f-string: put the letter f just before the opening quote, then put any variable or sum inside curly brackets {}. Python fills in the values.

name = "Sam"
age = 9
print(f"{name} is {age} years old.")
print(f"Next year {name} will be {age + 1}.")
Prints
Sam is 9 years old.
Next year Sam will be 10.

If you need a quote mark inside a string, use the other kind around it: "It's sunny" or 'She said "hi"'.

Practice

What does this print?

print("sun" + "flower")
More info

Quick reference

a + bJoin two strings. No space is added.
s * 3The string repeated three times.
len(s)How many characters s has.
s[0], s[-1]The first and last characters. Indexes start at 0.
s.upper() s.lower() s.replace(a, b)Methods that give back a changed copy.
f"{x}"An f-string: values in {} are filled in.

Related courses