str.format() / f-strings / str.zfill()
Methods and syntax for embedding values into strings and formatting them. f-strings are the most modern and readable approach.
Syntax
# Embed values using the format() method.
"template {}".format(value)
"template {name}".format(name=value)
"template {format_spec}".format(value)
# Embed variables directly using f-strings (Python 3.6+).
f"text {variable} text"
f"text {expression:.2f} text"
# Pad a number with leading zeros.
string.zfill(width)
# Align a string within a specified width.
string.center(width, fillchar=' ')
string.ljust(width, fillchar=' ')
string.rjust(width, fillchar=' ')
Method List
| Method / Syntax | Description |
|---|---|
| str.format(*args, **kwargs) | Returns a formatted string by substituting values into the {} placeholders of a template string. |
| f"...{expression}..." | Prefixing a string literal with f lets you embed variables or expressions directly inside {}. This is the most Pythonic approach. |
| str.zfill(width) | Pads the string on the left with zeros until it reaches the specified width. |
| str.center(width, fillchar) | Centers the string within a field of the specified width. |
| str.ljust(width, fillchar) | Left-aligns the string within the specified width, padding the right side with the fill character. |
| str.rjust(width, fillchar) | Right-aligns the string within the specified width, padding the left side with the fill character. |
Sample Code
# Basic usage of f-strings (the most modern approach).
name = "Taro"
age = 20
print(f"Name: {name}, Age: {age}") # Name: Taro, Age: 20
# Evaluate an expression inside an f-string.
price = 1980
tax_rate = 0.1
print(f"Price with tax: {price * (1 + tax_rate):.0f}") # Price with tax: 2178
# Format numbers with format specifiers.
pi = 3.14159265
print(f"Pi: {pi:.2f}") # Pi: 3.14 (2 decimal places)
print(f"Pi: {pi:.4f}") # Pi: 3.1416
print(f"Amount: {1000000:,}") # Amount: 1,000,000 (with comma separator)
print(f"Ratio: {0.856:.1%}") # Ratio: 85.6% (percentage notation)
# Format a number in different bases.
n = 255
print(f"Decimal: {n:d}, Hex: {n:x}, Binary: {n:b}, Octal: {n:o}")
# Decimal: 255, Hex: ff, Binary: 11111111, Octal: 377
# Align strings within a field width.
print(f"{'left':<10}|") # left |
print(f"{'center':^10}|") # center |
print(f"{'right':>10}|") # right|
# Using format() for compatibility with Python 3.5 and earlier.
print("Name: {}, Age: {}".format(name, age))
print("Name: {name}, Age: {age}".format(name="Hanako", age=25))
print("{0} and {1} and {0}".format("A", "B")) # A and B and A
# Applying format specifiers with format().
print("Amount: {:,}".format(1234567)) # Amount: 1,234,567
print("Ratio: {:.1%}".format(0.856)) # Ratio: 85.6%
# Zero-padding with zfill().
order_no = "42"
print(order_no.zfill(6)) # 000042 (pads with zeros to 6 digits)
# Zero-pad month and day values.
month = 3
day = 5
print(f"{month:02d}/{day:02d}") # 03/05
# Aligning text with center(), ljust(), and rjust().
label = "PYTHON"
print(label.center(20, "=")) # =======PYTHON=======
print(label.ljust(20, "-")) # PYTHON--------------
print(label.rjust(20, "-")) # --------------PYTHON
Notes
Python offers three main ways to format strings: f-strings, format(), and the % operator. In modern Python (3.6+), f-strings are recommended because they are the most readable and the fastest. Inside an f-string, you can write not only variables but also arbitrary expressions and function calls.
The format specifier syntax follows the pattern :flags width.precision type. Learning the most commonly used specifiers will make your code much more concise. To display a floating-point number as an integer, use {:.0f} (zero decimal places). Using {:d} on a float will raise a TypeError.
When debugging, you can write f"{variable_name=}" (Python 3.8+) to print both the variable name and its value at once. For example, f"{pi=}" outputs pi=3.14159265. For numeric type conversions, see int() / float() / str().
If you find any errors or copyright issues, please contact us.