Python Format Strings
In this page:
"text {} and {}".format(value1, value2)
"text {name}".format(name=value)
Basic .format() Method
The .format() method replaces {} placeholders in a string with the arguments you pass to it, in the order they appear — "{} is {}".format(name, age) — letting you build readable strings without manually concatenating pieces with +.
Example: Basic .format() Method
name = "Alex"
age = 30
print("{} is {}".format(name, age)) # {} placeholders filled in order
Named Placeholders
Giving placeholders names instead of leaving them positional, like "{name} is {age}".format(name=name, age=age), makes the template self-documenting and immune to bugs caused by arguments being passed in the wrong order.
Example: Named Placeholders
name = "Alex"
age = 30
print("{name} is {age}".format(name=name, age=age)) # named placeholders, order-independent
Formatting Decimals
Adding a colon and format spec inside the braces, such as {:.2f}, controls how a number is displayed — in this case, rounding a float to exactly two decimal places, which is essential for anything involving currency or percentages.
Example: Formatting Decimals
price = 19.999
print("{:.2f}".format(price))
Alignment and Padding
Field-width and alignment specifiers let you pad values to a fixed width and choose < for left, > for right, or ^ for center alignment — the standard technique for lining up columns of numbers or text in console output.
Example: Alignment and Padding
print("{:<10}|".format("left")) # < left-aligns within a width of 10
print("{:>10}|".format("right")) # > right-aligns within a width of 10
print("{:^10}|".format("mid")) # ^ centers within a width of 10
Reusing Arguments
Including index numbers inside the braces, like "{0} {1} {0}", lets a single argument be reused multiple times or displayed out of the order it was passed, without duplicating the value in the function call itself.
Example: Reusing Arguments
print("{0} {1} {0}".format("echo", "middle"))
- Providing fewer arguments than placeholders, e.g.
"{} {}".format(a), which raisesIndexError. - Mixing automatic
{}and manual{0}numbering in one string, which raisesValueError. - Using the wrong format spec such as
"{:d}".format(3.5), which raisesValueError; use{:.1f}for floats.
Chapter Quiz — Complete all 16 topics to unlock
0/16 topics done
Complete these topics first:
- Python print()
- Python input()
- Python Format Strings
- Python f-strings
- Python String Formatting
- Python Arithmetic Operators
- Python Relational Operators
- Python Logical Operators
- Python Bitwise Operators
- Python Assignment Operators
- Python Increment & Decrement
- Python Ternary Operator
- Python Operator Precedence
- Python Identity Operators
- Python Membership Operators
- Python Operators