Strings: working with text

Text in Python is a string. Join strings, repeat them, measure them with len, mix in numbers safely, and build messages with f-strings.

Lesson · 15 min

In this lesson you will

  • Write strings with single, double and triple quotes
  • Join and repeat strings with + and *
  • Measure a string's length with len()
  • Combine text and numbers with str() and with f-strings
  • Use \n for a new line

Most of what people read on a screen is text: names, messages, labels, receipts. In Python a piece of text is called a string, type str. You’ve already written plenty of them; now let’s learn what you can do with them.

Making strings

A string is any sequence of characters between matching quote marks. Letters, digits, spaces, punctuation and even emoji all count as characters.

greeting = "Hello"
place = 'the moon'
empty = ""
print(greeting, place)
print(type(empty))

"" is the empty string: a string with no characters in it. It’s still a string, the way an empty box is still a box.

Why two kinds of quotes? So you can put one kind inside the other:

print("It's a lovely day")
print('She said "wow" and left')

If you need several lines, use triple quotes, and the line breaks become part of the string:

poem = """Roses are red,
Python is neat,
Errors are friendly,
And can't be beat."""
print(poem)

Special characters

Inside a string, a backslash starts a special code. The one you’ll use most is \n, which means new line. \t is a tab.

print("Line one\nLine two")
print("Name:\tAda")

Joining and repeating

You saw in the lesson on types that + joins strings. This is called concatenation. The * operator repeats a string a whole number of times:

first = "Ada"
last = "Lovelace"
full = first + " " + last
print(full)
print("ha" * 3)
print("=" * 20)

Notice the " " in the middle. + glues strings together exactly, with no space added; if you want a space you have to put one in.

How long is it?

len() gives the length of a string: how many characters it holds. Spaces and punctuation count.

print(len("Python"))
print(len("hi there!"))
print(len(""))

Mixing text and numbers

Here’s a mistake everyone makes once. Predict what happens:

age = 12
print("I am " + age + " years old")

Python refuses:

TypeError: can only concatenate str (not "int") to str

+ can join two strings, or add two numbers, but it doesn’t know what “text plus number” should mean, so it stops rather than guess. There are two fixes. One is to convert the number to a string with str():

age = 12
print("I am " + str(age) + " years old")

f-strings: the easy way

The second fix is the one Python programmers use every day: an f-string. Put the letter f just before the opening quote, then write any variable or expression inside curly braces. Python replaces each one with its value:

name = "Mia"
age = 12
print(f"{name} is {age} years old")
print(f"Next year {name} will be {age + 1}")

No str(), no +, no fiddling with spaces. You can also control how numbers look. A colon after the value starts a format: :.2f means “as a decimal with 2 digits after the point”, perfect for money.

price = 3.5
quantity = 3
print(f"Total: ${price * quantity:.2f}")
print(f"Pi is roughly {3.14159:.3f}")

You’ll learn many more f-string tricks in a later section; :.2f is all you need for the lab at the end of this one.

Strings are not numbers, even when they look like them

Text that looks like a number is still text until you convert it:

a = "5"
b = "10"
print(a + b)
print(int(a) + int(b))

When data arrives from the outside world (a file, a web page, a form someone typed into) it nearly always arrives as strings. Converting to the right type is often the very first job.

A few handy extras

Strings come with built-in actions called methods, written with a dot after the string. You’ll study them properly later, but here are three you can use straight away:

shout = "hello there"
print(shout.upper())
print("QUIET PLEASE".lower())
print("  tidy me  ".strip())

Your turn

Exercise · Python

Name badge

Make a conference name badge. Using the variables first, last, role and year, build:

  • full_name: first and last name with one space between, "Grace Hopper",
  • badge: the text "Grace Hopper (Admiral) since 1934", built from the variables (an f-string is easiest; year is a number),
  • border: a line of * characters exactly as long as badge (use len).

Then print border, badge, border on three lines. Your code should still work if someone changes the four variables at the top.

first = "Grace"
last = "Hopper"
role = "Admiral"
year = 1934

full_name = first + last
badge = ""
border = ""

Check yourself

Self-check · 4 questions

Strings

1. What is len("hi there")?
2. What does "ab" * 3 give?
3. Why does "Age: " + 12 cause an error?
4. If name = "Ana", what does f"Hi {name}!" give?