Python
f-strings
print function
string formatting
Python programming

What is printf...

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

print(f"...") in Python combines the print() function with f-strings (formatted string literals), introduced in Python 3.6. The f prefix before the string tells Python to evaluate expressions inside curly braces {} and insert their values into the string. F-strings are the fastest and most readable string formatting method in Python, replacing older approaches like % formatting and .format(). This article covers f-string syntax, formatting options, and comparisons with other methods.

Basic F-String Syntax

python
1name = "Alice"
2age = 30
3
4# F-string — expressions inside {}
5print(f"Hello, {name}! You are {age} years old.")
6# Hello, Alice! You are 30 years old.
7
8# Any expression works inside {}
9print(f"Next year you'll be {age + 1}.")
10# Next year you'll be 31.
11
12# Method calls
13print(f"Name uppercase: {name.upper()}")
14# Name uppercase: ALICE
15
16# Ternary expression
17status = "adult" if age >= 18 else "minor"
18print(f"{name} is an {status}.")
19# Alice is an adult.

Everything inside {} is evaluated as a Python expression at runtime. The result is converted to a string and inserted into the output.

Number Formatting

python
1price = 49.99
2quantity = 1234567
3pi = 3.14159265
4
5# Decimal places
6print(f"Price: ${price:.2f}")           # Price: $49.99
7print(f"Pi: {pi:.4f}")                  # Pi: 3.1416
8
9# Thousands separator
10print(f"Quantity: {quantity:,}")         # Quantity: 1,234,567
11print(f"Quantity: {quantity:_}")         # Quantity: 1_234_567
12
13# Percentage
14ratio = 0.856
15print(f"Accuracy: {ratio:.1%}")         # Accuracy: 85.6%
16
17# Padding and alignment
18for i in range(1, 4):
19    print(f"Item {i:>3}: ${i * 10.5:<8.2f}")
20# Item   1: $10.50
21# Item   2: $21.00
22# Item   3: $31.50
23
24# Binary, octal, hex
25n = 255
26print(f"Binary: {n:b}")    # Binary: 11111111
27print(f"Octal: {n:o}")     # Octal: 377
28print(f"Hex: {n:x}")       # Hex: ff
29print(f"Hex: {n:#x}")      # Hex: 0xff

The format spec after : controls width, alignment, precision, and type.

String Formatting

python
1text = "hello"
2
3# Width and alignment
4print(f"|{text:<20}|")   # |hello               |  (left)
5print(f"|{text:>20}|")   # |               hello|  (right)
6print(f"|{text:^20}|")   # |       hello        |  (center)
7print(f"|{text:*^20}|")  # |*******hello********|  (center with fill)
8
9# Truncation
10long_text = "This is a very long string"
11print(f"{long_text:.10}")  # This is a

Multiline F-Strings

python
1name = "Alice"
2role = "Engineer"
3salary = 95000
4
5# Multiline with triple quotes
6report = f"""
7Employee Report
8===============
9Name:   {name}
10Role:   {role}
11Salary: ${salary:,.2f}
12"""
13print(report)
14
15# Or join multiple f-strings
16lines = (
17    f"Name: {name}\n"
18    f"Role: {role}\n"
19    f"Salary: ${salary:,.2f}"
20)
21print(lines)

F-Strings vs Other Methods

python
1name = "Alice"
2age = 30
3
4# 1. F-string (Python 3.6+) — recommended
5print(f"{name} is {age}")
6
7# 2. str.format() (Python 2.7+)
8print("{} is {}".format(name, age))
9print("{name} is {age}".format(name=name, age=age))
10
11# 3. % formatting (C-style, oldest)
12print("%s is %d" % (name, age))
13
14# 4. Template strings (for untrusted input)
15from string import Template
16t = Template("$name is $age")
17print(t.substitute(name=name, age=age))

F-strings are fastest because they are compiled to efficient bytecode at parse time, while .format() and % require runtime parsing.

Debugging with F-Strings (Python 3.8+)

python
1x = 42
2y = "hello"
3items = [1, 2, 3]
4
5# The = sign shows the expression AND its value
6print(f"{x = }")         # x = 42
7print(f"{y = }")         # y = 'hello'
8print(f"{len(items) = }")  # len(items) = 3
9print(f"{x * 2 = }")    # x * 2 = 84

The = specifier (Python 3.8+) prints both the expression text and its value, which is convenient for quick debugging.

Escaping Braces and Quotes

python
1# Literal curly braces — double them
2print(f"Use {{braces}} in f-strings")
3# Use {braces} in f-strings
4
5# Quotes inside f-strings
6name = "Alice"
7print(f"She said, 'Hello {name}'")       # Single inside double
8print(f'She said, "Hello {name}"')       # Double inside single
9print(f"She said, \"Hello {name}\"")     # Escaped

Common Pitfalls

  • Using f-strings before Python 3.6: F-strings are a syntax error in Python 3.5 and earlier. Use .format() for compatibility with older Python versions.
  • Backslashes inside f-string expressions: f"path: {path\n}" is a syntax error. Assign the expression to a variable first: newline = '\n'; f"path: {newline}".
  • Security with untrusted input: F-strings evaluate arbitrary expressions. Never use eval(f"...") or construct f-strings from user input. Use Template strings for untrusted data.
  • Missing the f prefix: print("Hello, {name}") prints the literal text {name} instead of the variable value. The f prefix is required for expression evaluation.
  • Complex expressions reducing readability: f"{data[key].method(arg1, arg2).attr:.2f}" is hard to read. Extract complex expressions to variables before the f-string.

Summary

  • print(f"...") combines Python's print() with f-string formatting for inline expression evaluation
  • Use : inside braces for number formatting: {value:.2f} (decimals), {value:,} (thousands), {value:.1%} (percent)
  • F-strings are the fastest Python string formatting method — prefer them over .format() and %
  • Use {expr = } (Python 3.8+) for quick debug printing that shows both expression and value
  • Double braces {{}} for literal curly braces in the output
  • Never use f-strings with untrusted input — use Template strings instead

Course illustration
Course illustration

All Rights Reserved.