I. Overview of String Formatting
1.1 What Is String Formatting?
String formatting is the process of embedding variables, constants, or calculation results into a string according to specified rules.
For example, suppose you need to output user information:
name = "Alice"
age = 25
message = "姓名:Alice,年龄:25"
Writing a fixed string directly cannot accommodate dynamic data. String formatting can insert variables into a template:
name = "Alice"
age = 25
message = f"姓名:{name},年龄:{age}"
print(message)
String formatting mainly solves the following problems:
- Insert variables dynamically.
- Control numeric precision.
- Control text alignment and padding.
- Format dates, amounts, and percentages.
- Generate logs, reports, and prompt messages.
- Build structured output.
1.2 Three Main String Formatting Methods in Python
| Method | Typical Syntax | Introduced In | Characteristics |
|---|---|---|---|
% formatting |
"Hello %s" % name |
Early Python versions | Similar to C's printf |
str.format() |
"Hello {}".format(name) |
Python 2.6 / 3.0 | Uses {} placeholders |
| f-string | f"Hello {name}" |
Python 3.6 | Supports embedding expressions directly |
All three methods can implement variable substitution, but their internal mechanisms and applicable scenarios differ.
flowchart TD
A["String formatting requirement"] --> B["Choose formatting method"]
B --> C["Percent formatting %"]
B --> D["str.format()"]
B --> E["f-string"]
C --> F["Generate formatted string"]
D --> F
E --> F
F --> G["Output, store, or pass text"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
II. Percent Sign Formatting (%)
2.1 Basic Syntax
Percent sign formatting is an earlier string formatting method provided by Python, and its syntax is similar to the printf style in C.
Basic form:
"格式字符串" % 值
Example:
name = "Alice"
age = 25
message = "Name: %s, Age: %d" % (name, age)
print(message)
# Name: Alice, Age: 25
In the format string, %s and %d are format specifiers, specifying the output format for strings and integers, respectively.
2.2 Common Format Specifiers
| Format specifier | Meaning | Example |
|---|---|---|
%s |
String form | "%s" % "Python" |
%r |
The object's repr representation | "%r" % "Python" |
%d |
Decimal integer | "%d" % 10 |
%i |
Integer | "%i" % 10 |
%f |
Fixed-point float | "%f" % 3.14 |
%e |
Scientific notation | "%e" % 1000 |
%g |
General format chosen based on the value | "%g" % 3.14 |
%x |
Lowercase hexadecimal integer | "%x" % 255 |
%X |
Uppercase hexadecimal integer | "%X" % 255 |
%o |
Octal integer | "%o" % 8 |
%% |
Outputs a percent sign | "%%" |
Example:
number = 255
price = 19.9876
name = "Python"
print("%s" % name)
print("%d" % number)
print("%f" % price)
print("%e" % price)
print("%x" % number)
print("%X" % number)
print("%o" % number)
print("完成率:90%%")
2.3 Formatting with multiple arguments
When multiple values need to be inserted, a tuple is usually used.
name = "Alice"
age = 25
score = 95.5
message = "Name: %s, Age: %d, Score: %.1f" % (
name,
age,
score
)
print(message)
A single value can also be used:
name = "Python"
print("Hello %s" % name)
If the format string contains only one placeholder, a single object can be supplied directly on the right-hand side.
Note that the number of placeholders and the number of arguments on the right-hand side must match; otherwise a TypeError may occur.
2.4 Precision control
Percent formatting can control the number of decimal places for floating-point numbers.
price = 19.98765
print("%.2f" % price) # 19.99
print("%.3f" % price) # 19.988
print("%.0f" % price) # 20
Format:
%.[precision]f
It can also limit the maximum output width of a string:
text = "Python"
print("%.3s" % text) # Pyt
2.5 Width and alignment
Percent formatting supports specifying the field width.
name = "Python"
print("%10s" % name)
print("%-10s" % name)
Meaning:
%10s: width 10, right-aligned by default.%-10s: width 10, left-aligned.
Zero padding can also be used:
number = 42
print("%05d" % number) # 00042
2.6 Formatting with dictionary arguments
Percent formatting also supports supplying named arguments via a dictionary.
user = {
"name": "Alice",
"age": 25
}
message = "Name: %(name)s, Age: %(age)d" % user
print(message)
This approach avoids errors in matching multiple positional arguments, but the syntax is relatively complex.
2.7 Limitations of percent formatting
Percent formatting is simple, but it has some limitations:
- Placeholders and arguments correspond by position; when there are many arguments, readability decreases.
- Format specifiers need to match the data type.
- It does not support writing Python expressions directly in placeholders.
- Complex formatting control is not as intuitive as modern formatting methods.
- It is not suitable for designing new complex string templates.
Therefore, new code usually prefers f-strings or str.format().
III. str.format() Formatting
3.1 Basic Syntax
str.format() uses {} as a field placeholder.
Basic form:
"format string".format(args)
Example:
name = "Alice"
age = 25
message = "Name: {}, Age: {}".format(name, age)
print(message)
Inside {} you can specify the argument position, argument name, and format control rules.
3.2 Positional Arguments
You can use numeric indices to specify argument positions.
message = "{0} is learning {1}".format(
"Alice",
"Python"
)
print(message)
# Alice is learning Python
Indices start from 0.
The same argument can be used repeatedly:
message = "{0} loves {1}, and {0} uses {1}".format(
"Alice",
"Python"
)
print(message)
You can also omit the indices and have them matched automatically in order:
message = "{} + {} = {}".format(10, 20, 30)
print(message)
Automatic numbering and explicit numbering should not be mixed in the same format string.
3.3 Named Arguments
Keyword arguments can be used to improve readability.
message = "Name: {name}, Age: {age}".format(
name="Alice",
age=25
)
print(message)
When there are many arguments, named arguments are usually easier to maintain than positional arguments.
3.4 Accessing Object Attributes
format() supports accessing object attributes via dot notation.
class User:
def __init__(self, name, age):
self.name = name
self.age = age
user = User("Alice", 25)
message = "Name: {0.name}, Age: {0.age}".format(user)
print(message)
You can also access elements in a dictionary or sequence:
user = {
"name": "Alice",
"age": 25
}
print("{0[name]}".format(user))
print("{0[age]}".format(user))
Note: The field access syntax is part of the formatting mechanism and is not equivalent to executing arbitrary Python expressions.
3.5 Format Specification
One of the most important capabilities of str.format() is controlling output through a format specification.
Basic syntax:
{field_name:format_spec}
For example:
price = 19.9876
print("{:.2f}".format(price))
# 19.99
The content after the colon : is the format spec.
The general structure of a format spec can be summarized as:
[[fill]align][sign][z][#][0][width][grouping_option][.precision][type]
The meaning of each part:
| Part | Purpose |
|---|---|
fill |
Fill character |
align |
Alignment |
sign |
Sign display policy |
z |
Normalize negative zero |
# |
Enable alternate forms such as base prefixes |
0 |
Use zero padding |
width |
Minimum field width |
grouping_option |
Digit grouping separator |
precision |
Precision control |
type |
Output type |
Among these, z is a format spec option introduced in Python 3.11, applicable to float formats that support it.
3.6 Alignment
| Alignment symbol | Meaning |
|---|---|
< |
Left-aligned |
> |
Right-aligned |
^ |
Centered |
= |
Pad after the sign and before the digits |
Example:
name = "Python"
print("{:<12}".format(name))
print("{:>12}".format(name))
print("{:^12}".format(name))
Specifying a fill character:
name = "Python"
print("{:-<12}".format(name))
print("{:->12}".format(name))
print("{:-^12}".format(name))
Output:
Python------
------Python
---Python---
The = alignment is mainly used for number formats, so that the padding appears between the sign and the digits:
print("{:0=+8d}".format(42))
# +0000042
3.7 Numeric precision control
For floating-point numbers, .precision controls the number of decimal places.
number = 3.1415926
print("{:.2f}".format(number))
print("{:.4f}".format(number))
For strings, precision usually means the maximum number of characters output:
text = "Python Programming"
print("{:.6}".format(text))
# Python
For different numeric types, the exact meaning of precision is determined by the format type.
For example:
number = 12345.6789
print("{:.2f}".format(number))
print("{:.3e}".format(number))
print("{:.5g}".format(number))
f: fixed-point format.e: scientific notation.g: chooses whichever of plain or scientific notation is more appropriate for the value.
3.8 Sign control
You can control whether a number displays a sign.
number = 42
print("{:+d}".format(number))
print("{: d}".format(number))
print("{:-d}".format(number))
Meaning:
+: show a sign for both positive and negative numbers.- Space: show a space before positive numbers, and a minus sign for negative numbers.
-: show a minus sign only for negative numbers; this is the default behavior.
3.9 Digit grouping
You can separate digits with commas or underscores.
number = 1234567890
print("{:,}".format(number))
print("{:_}".format(number))
Floating-point numbers support grouping as well:
number = 1234567.89
print("{:,.2f}".format(number))
This format is suitable for generating reports and displaying monetary amounts.
3.10 Base Formatting
Integers support binary, octal, and hexadecimal formats.
number = 255
print("{:b}".format(number))
print("{:o}".format(number))
print("{:x}".format(number))
print("{:X}".format(number))
Adding # displays the base prefix:
number = 255
print("{:#b}".format(number))
print("{:#o}".format(number))
print("{:#x}".format(number))
3.11 Percentage Formatting
Using the % type multiplies the value by 100 and adds a percent sign.
rate = 0.8567
print("{:.2%}".format(rate))
# 85.67%
Note that % in a format specification and the percent-sign formatting operator are not the same concept.
Here, % is a type specifier in a format format specification.
3.12 Dynamic Format Specifications
The format specification itself can also be provided by variables.
number = 3.1415926
precision = 3
result = "{:.{}f}".format(number, precision)
print(result)
# 3.142
You can also specify width and precision dynamically:
number = 3.1415926
width = 12
precision = 2
result = "{:{}.{}f}".format(
number,
width,
precision
)
print(result)
This allows format() to build configurable text output templates.
3.13 format() and the Formatting Protocol
str.format() does not simply convert all objects to strings.
It relies on Python's formatting protocol.
The core mechanisms include:
__format__(): Defines how an object generates a string according to a format specification.format(value, spec): Invokes an object's formatting protocol.str.format(): Parses template fields, then applies format specifications to field values.
For example:
number = 3.14159
print(format(number, ".2f"))
print("{:.2f}".format(number))
Both forms can ultimately use the formatting capabilities of float objects.
Custom classes can also implement __format__():
class Temperature:
def __init__(self, value):
self.value = value
def __format__(self, spec):
return format(self.value, spec) + "°C"
temperature = Temperature(36.5)
print(f"{temperature:.1f}")
# 36.5°C
This mechanism gives Python's formatting system good extensibility.
IV. f-string Formatting
4.1 What Is an f-string
An f-string (Formatted String Literal) is a formatted string literal introduced in Python 3.6.
By adding f or F before a string, you can embed expressions in curly braces {}.
name = "Alice"
age = 25
message = f"Name: {name}, Age: {age}"
print(message)
Unlike % and format(), f-strings can directly reference variables in the current scope without passing extra arguments.
4.2 Embedding Variables
name = "Python"
version = 3.14
print(f"{name} {version}")
Variables are read when the f-string is evaluated.
If a variable changes, reevaluating the f-string produces a new result:
name = "Alice"
message1 = f"Hello, {name}"
name = "Bob"
message2 = f"Hello, {name}"
print(message1) # Hello, Alice
print(message2) # Hello, Bob
Once a string has been created, it does not update automatically as the variable changes.
4.3 Embedded Expressions
Python expressions can be placed inside the curly braces of an f-string.
a = 10
b = 20
print(f"{a + b}")
print(f"{a * b}")
print(f"{max(a, b)}")
Calculations can be performed directly:
price = 100
quantity = 3
print(f"总金额:{price * quantity}")
Methods can also be called:
name = "python"
print(f"{name.upper()}")
# PYTHON
The expression is evaluated while the f-string is evaluated, and the result is then converted to text according to the formatting rules.
4.4 Conditional Expressions
Conditional expressions can be used in f-strings.
score = 85
message = f"结果:{'通过' if score >= 60 else '未通过'}"
print(message)
Function calls, indexing, and attribute access can also be used:
user = {
"name": "Alice",
"scores": [90, 85, 95]
}
print(f"姓名:{user['name']}")
print(f"最高分:{max(user['scores'])}")
4.5 Format Control
f-strings use the same format specification syntax as str.format().
price = 19.9876
print(f"{price:.2f}")
# 19.99
Alignment:
name = "Python"
print(f"{name:<12}")
print(f"{name:>12}")
print(f"{name:^12}")
Padding:
number = 42
print(f"{number:0>6}")
print(f"{number:*^10}")
Number grouping:
number = 1234567890
print(f"{number:,}")
print(f"{number:_}")
Percentage:
rate = 0.8567
print(f"{rate:.2%}")
Scientific notation:
number = 123456789
print(f"{number:.3e}")
4.6 f-string Debugging Expressions
Python 3.8 introduced f-string debugging expression syntax.
Adding = after an expression outputs both the expression text and the computed result.
name = "Alice"
age = 25
print(f"{name=}")
print(f"{age=}")
Output:
name='Alice'
age=25
Format specifications can also be combined:
price = 19.98765
print(f"{price=:.2f}")
This notation is suitable for debugging and temporary diagnostics.
4.7 Escaping Curly Braces in f-strings
f-strings use {} to mark expression boundaries.
To output literal curly braces, use double curly braces.
name = "Python"
print(f"{{name}}")
# {name}
To output a pair of curly braces:
print(f"{{Hello}}")
# {Hello}
This is not necessary in ordinary strings; it only needs attention in f-strings and related formatting templates.
4.8 Backslashes in f-strings
The expression part of an f-string is subject to Python syntax rules.
In Python 3.11 and earlier, the expression part cannot directly contain a backslash.
For example, the following form has syntax issues in these versions:
# Writing a backslash directly in the expression part is not allowed in older versions
# print(f"{'\n'.join(items)}")
You can compute the expression in advance:
items = ["Python", "Java", "Go"]
separator = "\n".join(items)
print(f"{separator}")
Python 3.12 introduced more flexible f-string parsing rules (PEP 701), relaxing some syntax restrictions in expressions, including quote reuse, backslashes, and comments.
However, for compatibility with older versions, it is still recommended to compute complex expressions in advance and keep format strings concise.
V. Execution Mechanism of f-strings
5.1 f-strings Are More Than String Replacement
An f-string is a string literal syntax.
For example:
name = "Alice"
message = f"Hello, {name.upper()}!"
It involves several processing steps:
- Parse the f-string literal.
- Identify plain text and expression fields.
- Compile the expression.
- Evaluate the expression at runtime.
- Convert the result according to the format specification.
- Combine the parts into the final string.
This can be summarized as:
flowchart TD
A["Read f-string source code"] --> B["Identify plain text and expression fields"]
B --> C["Parse and compile expression"]
C --> D["Evaluate at runtime"]
D --> E["Execute formatting protocol"]
E --> F["Combine string fragments"]
F --> G["Generate final str object"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px