str.format() / f-strings / str.zfill()
| Since: | Python 3.6(2016) |
|---|
Methods and syntax for embedding values into strings and formatting them. f-strings are a method available since Python 3.6.
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 {}. A method available since Python 3.6 and widely used. |
| 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
str_format_fstring.py
# Basic usage of f-strings (Python 3.6+).
name = "Kiryu Kazuma"
age = 37
print(f"Name: {name}, Age: {age}")
# Evaluate an expression inside an f-string.
price = 1980
tax_rate = 0.1
print(f"Price with tax: {price * (1 + tax_rate):.0f}")
# Format numbers with format specifiers.
pi = 3.14159265
print(f"Pi: {pi:.2f}")
print(f"Pi: {pi:.4f}")
print(f"Amount: {1000000:,}")
print(f"Ratio: {0.856:.1%}")
# Format a number in different bases.
n = 255
print(f"Decimal: {n:d}, Hex: {n:x}, Binary: {n:b}, Octal: {n:o}")
# Align strings within a field width.
print(f"{'left':<10}|")
print(f"{'center':^10}|")
print(f"{'right':>10}|")
Running the code produces the following output:
python3 str_format_fstring.py
Name: Kiryu Kazuma, Age: 37
Price with tax: 2178
Pi: 3.14
Pi: 3.1416
Amount: 1,000,000
Ratio: 85.6%
Decimal: 255, Hex: ff, Binary: 11111111, Octal: 377
left |
center |
right|
str_format_method.py
# Using format() for compatibility across Python versions.
name = "Kiryu Kazuma"
age = 37
print("Name: {}, Age: {}".format(name, age))
print("Name: {name}, Age: {age}, Song: {song}".format(name="Kiryu Kazuma", age=37, song="Baka Mitai"))
print("{0} and {1} and {0}".format("A", "B"))
# Applying format specifiers with format().
print("Amount: {:,}".format(1234567))
print("Ratio: {:.1%}".format(0.856))
Running the code produces the following output:
python3 str_format_method.py Name: Kiryu Kazuma, Age: 37 Name: Kiryu Kazuma, Age: 37, Song: Baka Mitai A and B and A Amount: 1,234,567 Ratio: 85.6%
str_format_align.py
# Zero-padding with zfill().
order_no = "42"
print(order_no.zfill(6))
# Zero-pad month and day values.
month = 3
day = 5
print(f"{month:02d}/{day:02d}")
# Aligning text with center(), ljust(), and rjust().
label = "PYTHON"
print(label.center(20, "="))
print(label.ljust(20, "-"))
print(label.rjust(20, "-"))
Running the code produces the following output:
python3 str_format_align.py 000042 03/05 =======PYTHON======= PYTHON-------------- --------------PYTHON
Common Mistakes
Common Mistake 1: Using {:d} with a float
The format specifier :d only works with integers. Using it with a float raises a ValueError. To display a float without decimal places, use :.0f instead.
mistake1_ng.py
pi = 3.14159265
# :d cannot be used with float
print(f"{pi:d}")
Running the code produces the following output:
python3 mistake1_ng.py ValueError: Unknown format code 'd' for object of type 'float'
mistake1_ok.py
pi = 3.14159265
# Use :.0f to display a float with zero decimal places.
print(f"{pi:.0f}")
Running the code produces the following output:
python3 mistake1_ok.py 3
Common Mistake 2: Too few arguments for format() placeholders
If the number of arguments passed to format() is fewer than the number of placeholders, an IndexError is raised. Using named placeholders prevents this mistake.
mistake2_ng.py
# Three placeholders but only two arguments
print("Name: {}, Age: {}, Song: {}".format("Kiryu Kazuma", 37))
Running the code produces the following output:
python3 mistake2_ng.py IndexError: Replacement index 2 out of range for positional args tuple
mistake2_ok.py
# Use named placeholders to be explicit.
print("Name: {name}, Age: {age}, Song: {song}".format(name="Kiryu Kazuma", age=37, song="Baka Mitai"))
# Or use an f-string.
name = "Kiryu Kazuma"
age = 37
song = "Baka Mitai"
print(f"Name: {name}, Age: {age}, Song: {song}")
Running the code produces the following output:
python3 mistake2_ok.py Name: Kiryu Kazuma, Age: 37, Song: Baka Mitai Name: Kiryu Kazuma, Age: 37, Song: Baka Mitai
Notes
Python offers three main ways to format strings: f-strings, format(), and the % operator. f-strings are widely used in Python 3.6 and later. 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 ValueError.
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.