Lesson 93 +10 XP

String Formatting

Formatting inserts values into a string. The modern way is f-strings; the older way is .format().

The % operator (old style)


python
price = 49
txt = "The price is %d dollars"
print(txt % price)

### The price is 49 dollars

%d is a placeholder for an integer. Other codes: %f for float, %s for string.

The format() method


python
txt = "The price is {} dollars"
print(txt.format(price))

### The price is 49 dollars

Multiple placeholders


python
item = "apple"
count = 3
price = 49.95
txt = "I want {} pieces of item {} for {} dollars"
print(txt.format(count, item, price))

Indexed placeholders


python
txt = "I have a {carname}, it is a {model}."
print(txt.format(carname="Ford", model="Mustang"))

Formatting numbers with format()


python
price = 49
txt = "The price is {:.2f} dollars"
print(txt.format(price))

### The price is 49.00 dollars

Formatting numbers with f-strings


python
price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)

### The price is 59.00 dollars

Alignments and separators

  • :> right-align, :< left-align, :^ center.
  • :, thousands separators.

python
print(f"{1234567:,}")

### 1,234,567
print(f"{'hi':^10}")

### centered in 10 spaces

TL;DR

  • %d, %f, %s are old-style placeholders.
  • .format() uses {} placeholders.
  • f-strings are the modern, recommended way.
  • Specifiers like :.2f and :, format numbers.