Home Tutorials Python Tutorial String Formatting
String Formatting

String Formatting


Definition: String formatting is the process of dynamically inserting variables, expressions, or values directly into a string literal to build structured, clean, and dynamic text outputs.

Why: Manually joining text and numbers using the + operator can easily lead to confusing syntax and errors (like forgetting to convert numbers to strings). String formatting provides a clean, elegant way to design outputs like user notifications, reports, and logs.

The Modern Standard: F-Strings (Formatted String Literals)

Introduced in Python 3.6, f-strings are the preferred and most popular way to format text. You simply place an f or F right before the opening quote and write your variables directly inside curly brackets { }.

Example

name = "Anu"
score = 95

# Using an f-string to format the output
print(f"{name} scored {score} marks.")

Explanation

  • The f Prefix: The letter f tells Python to look inside the string for placeholder expressions to evaluate.
  • Curly Brackets: Python evaluates the variables inside {name} and {score} and replaces them seamlessly with "Anu" and "95" when printing.

Advanced Formatting Capabilities

F-strings can do much more than display simple variables; they can also evaluate math operations or format number displays directly inside the brackets:

# 1. Performing math inside an f-string
print(f"Next year, you will be {age + 1} years old.")

# 2. Formatting decimal places (e.g., rounding to 2 decimal places)
price = 49.9567
print(f"The total is ${price:.2f}")  # Output: The total is $49.96

Key Notes

  • Older Methods: While f-strings are the modern standard, you might still encounter older codebases using the .format() method (e.g., "{} scored {} marks.".format(name, score)) or string interpolation using the % operator.
  • You can use any valid Python expression inside the curly brackets, such as calling functions or string methods (e.g., {name.upper()}).
  • F-strings are evaluated at runtime, making them incredibly fast and efficient compared to older formatting methods.
Example

🏋️ Test Yourself With Exercises

Take our quiz on String Formatting to test your knowledge.

Exercise »