PyPyPath

Module 4: Strings in Python

Formatting Strings

Often you want to mix text with variables — like a greeting with a name. f-strings are the recommended way to format strings in modern Python.

About 10 minutes

f-strings (recommended)

Put f before the quotes. Inside {}, write a variable or expression.

Example code
name = "Sam"
age = 20
print(f"Hello, {name}!")
print(f"Next year you will be {age + 1}")

.format() method

Example code
city = "London"
print("I live in {}".format(city))
print("I live in {0}".format(city))

Comma in print()

Example code
score = 95
print("Your score is", score)

For data science, f-strings are perfect for quick labels in charts and reports.

Practice

Use an f-string to print: Hello, NAME! You have N items.

Key takeaways

  • f"...{variable}..." is the clearest way to format strings.
  • .format() and print(a, b) also work.
  • You can put expressions inside {} in f-strings.

Quick check: Formatting Strings

Question 1 of 2

With name = "Ann", what does print(f"Hi {name}") show?