F-Strings

F-strings (formatted string literals) let you embed variables and expressions directly inside a string. Put an f before the opening quote and use {} to insert values.

Example

name = "Riley"
age = 17
print(f"Hi, I'm {name} and I'm {age} years old.")
# outputs: Hi, I'm Riley and I'm 17 years old.

Why Use F-Strings?

Compare these three ways to build the same string:

# String concatenation (clunky with numbers)
print("Score: " + str(score) + " points")

# Multiple print arguments (adds spaces)
print("Score:", score, "points")

# F-string (clean and readable)
print(f"Score: {score} points")

F-strings are usually the cleanest option.

Embed Expressions

You can put any Python expression inside the curly braces:

price = 19.99
print(f"Total with tax: {price * 1.08}")
# outputs: Total with tax: 21.5892

x = 5
print(f"{x} squared is {x ** 2}")
# outputs: 5 squared is 25

String Methods in F-Strings

You can call string methods directly inside the braces:

name = "alex"
print(f"Hello, {name.upper()}!")
# outputs: Hello, ALEX!

print(f"Hello, {name.title()}!")
# outputs: Hello, Alex!

Text Alignment with ljust(), rjust(), center()

These methods pad a string to a specific width:

label = "Name"
print(f"| {label.ljust(15)} |")   # left-align
# outputs: | Name            |

print(f"| {label.rjust(15)} |")   # right-align
# outputs: |            Name |

print(f"| {label.center(15)} |")  # center
# outputs: |      Name       |

Common use case — aligning columns:

items = [("Apples", 3), ("Bananas", 12), ("Oranges", 7)]
for item, count in items:
    print(f"{item.ljust(10)} {count}")

Output:

Apples     3
Bananas    12
Oranges    7

Combining with Other String Operations

F-strings work great with string multiplication for building patterns:

width = 20
print(f"+{'-' * (width - 2)}+")
# outputs: +------------------+

rating = 4
stars = "★" * rating + "☆" * (5 - rating)
print(f"Rating: {stars}")
# outputs: Rating: ★★★★☆

Common Mistakes

Forgetting the f prefix

# Wrong - prints literal {name}
print("Hello, {name}!")

# Right
print(f"Hello, {name}!")

Using quotes inside that match the outer quotes

# Wrong - syntax error
print(f"They said "hello"")

# Right - use different quotes
print(f'They said "hello"')
print(f"They said 'hello'")