Python String Formatting Basics
String formatting is one of the most powerful and convenient tools in Python. It gives you flexible control over how information is displayed in various development scenarios. Whether you're generating reports, writing log files, or building a user interface, well-formatted text is key to how information is perceived.
String formatting becomes especially important when working with numeric data, dates, tables, and multi-level templates. Proper text formatting significantly improves code readability, simplifies debugging and logging, and enhances how results appear in user interfaces.
In professional development environments, formatted strings are often a core part of templates, configuration files, and HTML reports. Using this tool correctly helps you write more maintainable and understandable code.
Three Main Formatting Approaches
Python offers developers three main methods for string formatting:
- f-strings — the modern approach, available since Python 3.6
- The .format() method — a versatile way compatible with older versions
- % formatting — the classic style inherited from the C language
In this article, we'll dive deep into each method. Special attention will be given to f-strings as the most readable and performant formatting option. We'll also cover formatting different number types, including decimals, percentages, and scientific notation. You'll learn text alignment techniques, working with templates, and practical examples from real-world projects.
f-strings: The Modern Formatting Standard
Basic Syntax and Capabilities
f-strings were introduced in Python 3.6 and revolutionized code convenience and readability. These are special string literals that start with the prefix f before the opening quote. Inside these strings, you can place variables and expressions inside curly braces {}.
name = "John"
age = 30
print(f"Hi, my name is {name} and I am {age} years old.")
The key advantage of f-strings is that you can use not just variables, but any valid Python expression:
print(f"In 5 years, I will be {age + 5} years old.")
You can also call functions and methods inside f-strings:
def square(x):
return x * x
print(f"The square of 4 is: {square(4)}")
Advanced f-string Features
f-strings support accessing object attributes and collection elements:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Maria", 25)
print(f"Employee: {person.name}, age: {person.age}")
data = {"city": "New York", "population": 8336000}
print(f"City {data['city']} with a population of {data['population']:,} people")
Number Formatting in f-strings
f-strings provide powerful options for formatting numeric values:
pi = 3.1415926
print(f"Pi to two decimal places: {pi:.2f}") # 3.14
| Syntax | Purpose | Example Output |
|---|---|---|
:.2f |
two decimal places (float) | 3.14 |
:,.2f |
with thousands separator | 1,234.56 |
:e |
scientific notation | 3.14e+00 |