Lesson 20 +10 XP

Concatenate and Format Strings

Concatenate and Format Strings

Concatenation joins strings; formatting inserts values into a template.

Concatenate with +

a = "Hello"
b = "World"
c = a + " " + b
print(c)  # Hello World

Glue with * and numbers

print("ab" * 3)  # ababab

f-strings (recommended)

Prefix the string with f and put variables inside { }:

age = 36
txt = f"My name is John, I am {age}"
print(txt)  # My name is John, I am 36

Formatting numbers in f-strings

Use a colon and a format specifier:

price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)  # The price is 59.00 dollars
  • :.2f means two decimal places.
  • :> right-align, :< left-align, :^ center.

The old .format() method

txt = "I am {} years old".format(36)
print(txt)  # I am 36 years old

Placeholders for commas

Add commas for thousands separators:

txt = f"The number is {1234567:,}"
print(txt)  # The number is 1,234,567

TL;DR

  • + joins strings; * repeats them.
  • f-strings put values in with {name}.
  • Use specifiers like :.2f and :, inside the braces.
  • .format() is the older alternative.