← Back to Python Course | Chapter 2: Input, Output & Operators | Lesson 3 of 16

Python Format Strings

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

python
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

python
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

python
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

python
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

python
print("{0} {1} {0}".format("echo", "middle"))

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.