Python Format Strings
In this page:
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))
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))
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"))
print("{:>10}|".format("right"))
print("{:^10}|".format("mid"))
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"))
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