Codiqo

Learn Python · lesson 5 of 60 · about 6 minutes

Joining and Formatting Text

Mix words and numbers in your assistant's messages with f-strings, and draw a divider by repeating text.

What you'll learn

  • Join strings with +
  • Repeat a string with *
  • Insert values into text with f-strings

Numbers in your messages

Your assistant's messages mix words and numbers, and + only joins text to text. "Saved: " + 45 doesn't work at all: Python won't join a string and a number, because it can't tell whether you meant to add or to join.

Two ways around it, both a little clumsy

saved = 45
print("Saved: " + str(saved))
print("Saved:", saved)

Output

Saved: 45
Saved: 45

f-strings

Put an f just before the opening quote and you get an f-string. Anything inside curly braces { } is worked out and dropped into the text, and numbers are turned into text for you. The spaces are part of the sentence, so you can see them.

Values and sums inside the braces

name = "Sam"
saved = 45
price = 120
print(f"{name} has saved {saved} of {price}.")
print(f"Still to go: {price - saved}")

Output

Sam has saved 45 of 120.
Still to go: 75

Repeating text

* with a string and a number repeats the string. "-" * 20 gives a divider line of 20 dashes, handy for splitting your assistant's output into sections.

* repeats a string

print("=" * 10)
print("ha" * 3)

Output

==========
hahaha

Tip

Forgetting the f is the most common mistake: without it, the braces and the name inside them are printed as they are.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.