Python String format() Method

The format() method is used to format strings by inserting values into placeholders defined by curly braces {} within a string.

Syntax

string.format(value1, value2, ...)

Parameters

value1, value2, ... (required): The values you want to insert into the string.

Return Value

Returns a new formatted string where the placeholders have been replaced with the specified arguments. The original string remains unchanged.

How It Works

  • The string contains curly braces {} as placeholders.
  • The format() method replaces these placeholders with the values you provide as arguments.

Examples

Using Position Arguments

Positional arguments are values passed to the format() method in order, and they are inserted into the string using empty or numbered placeholders like {}, {0}, {1}, etc.

Using Unnumbered Placeholders

print("{} is {} years old.".format("James", 45))
# Output: James is 45 years old.

Each {} gets replaced by the corresponding positional argument in the order they appear.

Using Numbered Placeholders

You can rearrange the output order by using index numbers inside the braces.

print("{1} is {0} years old.".format(45, "James"))
# Output: James is 45 years old.

Using Keyword Arguments

Keyword arguments allow you to insert values into named placeholders in a string, like {name}, {age}, etc.

print("{name} is {age} years old.".format(age=45, name="James"))
# Output: James is 45 years old.

Combining Positional and Keyword Arguments

You can use both positional and keyword arguments, but positional arguments must come before keyword arguments.

print("{} is {age} years old.".format("James", age=45))
# Output: James is 45 years old.

Formatting Numbers

The format() method allows you to control how numbers (integers, floats, etc.) are displayed in strings.

The syntax to format numbers is:

"{:format_spec}".format(number)

where,

  • : starts the format specification
  • format_spec defines how the number is displayed (width, precision, alignment, etc.).
print("{:.2f}".format(3.14159)) # Format float to two decimal places

print("{:5d}".format(45)) # Right-align integer in width 5 (add 3 spaces in front)

print("{:05d}".format(45)) # Zero-pad integer to width 5

print("{:,}".format(1234567))  # Format with thousand separator

print("{:.2%}".format(0.753422)) # Format as percentage with 2 decimal places

print("{:.2e}".format(1200)) # Format in scientific notation with 2 decimals

print("{:#x}".format(255)) # Format as lowercase hex with "0x" prefix

Output:

3.14
   45
00045
1,234,567
75.34%
1.20e+03
0xff

Using Multiple Specifiers

You can apply multiple specifiers in a single string.

print("{:,.2f}".format(12345.678)) # Output: 12,345.68

Padding And Alignment

You can align the text to the left, right, or center within a specified width. You can also choose a character to pad the extra space.

<: Left-aligns the text.

>: Right-aligns the text.

^: Center-aligns the text.

# Pad with spaces (default) to a width of 20
print("|{:<20}|".format("Left"))
print("|{:>20}|".format("Right"))
print("|{:^20}|".format("Center"))

# Pad with a specific character
print("{:*^20}".format("Centered"))

Output:

|Left                |
|               Right|
|       Center       |
******Centered******

Formatting Dictionaries

You can format strings using a dictionary with format() method by unpacking the dictionary into keyword arguments using the ** operator.

person = {"name": "James", "age": 35}
print("Name: {name} and Age: {age}".format(**person))

Output:

Name: James and Age: 35

You can use the format_map() method instead if you don’t want to unpack the dictionary.

Python Format Specifier

Here is a table of Python format specifiers:

SpecifierDescriptionExample
dDecimal"{:d}".format(45)  → "45"
bBinary "{:b}".format(10)"1010"
oOctal"{:o}".format(10)"12"
xHexadecimal (lowercase)"{:x}".format(10)"a"
XHexadecimal (uppercase)"{:X}".format(10)"A"
fFloating point"{:.2f}".format(3.1415)"3.14"
eScientific Notation (lowercase)"{:.2e}".format(1000)"1.00e+03"
EScientific Notation (uppercase)"{:.2E}".format(1000)"1.00E+03"
gGeneral format (e or f, whichever shorter"{:g}".format(1000000)"1e+06"
%Percentage (Multiplied by 100)"{:.2%}".format(0.5573)"55.73%"
0Zero padding for numbers"{:03d}".format(5)"005"
*Custom fill character"{:*^6}".format("Hi")"**Hi**"
,Thousand separator"{:,}".format(1000000)"1,000,000"
_ Underscore separator (Python 3.6+)"{:_}".format(1000000)"1_000_000"
# Alternate form (adds prefixes like 0x, 0o)"{:#o}".format(10)"0o12"
<Left align"{:<5}".format("Hi")"Hi   "
>Right align"{:>5}".format("Hi")"   Hi"
^Center align"{:^10}".format("Hi")"    Hi    "
=Pad after sign (for numbers)"{:=10}".format(-20)"-       20"
+Show sign for both positive and negative numbers"{:+}".format(20)"+20"
-Show sign for negative numbers only "{:-}".format(-20)"-20"
  (space)Use space for positive numbers"{: }".format(5)" 5"
.precisionPrecision (decimal places for floats, max characters for strings)"{:.2f}".format(3.1415)"3.14"