← Back to Chapters

Python String Formatting

? Python String Formatting

? Quick Overview

String formatting lets you insert variables and expressions into a string in a clean, readable way. Python supports several approaches, including modern f-strings and the older str.format() method, which help you control text, numbers, alignment and overall layout.

? Key Concepts

  • Use f-strings (f"...{expression}...") in Python 3.6+ for concise formatting.
  • Use the format() method for older Python versions or when f-strings are not available.
  • Apply positional and keyword placeholders for better control in templates.
  • Format numbers with a fixed number of decimal places (e.g., {pi:.2f}).
  • Control padding and alignment (left, right, center) to build neat tables and reports.

? Syntax and Theory

An f-string is written by prefixing a string with f, for example: f"My name is {name}". Any valid Python expression inside {...} will be evaluated and converted to a string.

The format() method works by using placeholders inside a string: "My name is {}".format(name). You can also use numbered placeholders ({0}, {1}) or named placeholders ({n}, {a}).

For numbers, you can add a format specifier after a colon, such as {pi:.2f} (2 decimal places) or {pi:10.3f} (width 10, 3 decimal places). Alignment uses < (left), > (right) and ^ (center) along with a width, for example {text:<10}.

? Code Examples

? Basic f-string example
name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old."
print(message)
? Using the format() method
name = "Alice"
age = 25
message = "My name is {} and I am {} years old.".format(name, age)
print(message)
? Positional and keyword arguments
name = "Alice"
age = 25

message1 = "Name: {0}, Age: {1}".format(name, age)
message2 = "Name: {n}, Age: {a}".format(n=name, a=age)

print(message1)
print(message2)
? Formatting numbers
pi = 3.14159

print(f"Pi rounded: {pi:.2f}")          # 3.14
print("Pi rounded: {:.3f}".format(pi))  # 3.142
? Padding and alignment with f-strings
text = "Python"

print(f"{text:<10}X")   # Left align
print(f"{text:>10}X")   # Right align
print(f"{text:^10}X")   # Center align

? Live Output and Explanation

? What these examples do

  • The basic f-string and format() examples both print: My name is Alice and I am 25 years old.
  • The positional/keyword example prints: Name: Alice, Age: 25 twice, once using positions and once using named placeholders.
  • The number formatting example rounds 3.14159 to: 3.14 (2 decimal places) and 3.142 (3 decimal places).
  • The alignment example prints the word Python inside a field of width 10, with an extra X character showing where the padding ends: left-aligned, right-aligned, and centered.

Together, these examples show how formatting helps you build clean, readable console output and properly aligned text for tables, logs, and reports.

✅ Tips

  • Prefer f-strings for readability and efficiency in Python 3.6+.
  • Use .format() when you must support Python versions earlier than 3.6.
  • Control decimals and alignment for clean output in reports, tables, and logs.
  • Always validate variable types before formatting to avoid errors.
  • Do not forget the f prefix when using f-strings, otherwise {...} will not be evaluated.
  • When using format(), make sure placeholders and arguments match to avoid IndexError or KeyError.

? Practice Tasks

  • Create a greeting message using an f-string with your name and favorite programming language.
  • Format a floating-point number to 2 decimal places using both an f-string and the format() method.
  • Align three different words in a table-like layout using f-string alignment (<, >, ^).
  • Use keyword arguments in format() to neatly display your name, age, and city.