Python String format() Method

Although you can get a lot done with the string methods, Python also provides a more advanced and powerful way to do string processing tasks – string formatting.

It allows you to embed variables inside a string.

format() Method Syntax

The syntax of format method is:

Python String format() Method Syntax

The format() method is invoked on a string known as Format string.

The format string contains one or more ‘placeholders‘ surrounded by curly braces {}.

The placeholder specifies the field whose value is to be formatted and inserted into the output.

Anything that is outside of the placeholder remains unchanged.

Python Format Specifier

Each placeholder contains the ‘Format specification’ to define how the value should be presented.

The general structure of standard format specifier is:

Python String Format Specifier

Here are all the formatting options:

String formatting options
Formatting optionsValid values
field<any number or keyword>
conversions | r | a
fill<any character>
align< | > | = | ^
sign+ | |
width<any number>
group_ | ,
precision<any number>
typeb | c | d | e | E | f | F | g | G | n | o | s | x | X | %

Simple Formatting

You can use format() method to do simple positional formatting. Just add a pair of curly braces where you want to substitute the value.

# Access arguments by default order (implicit)
S = '{} is {} years old.'.format('Bob', 25)

# Prints Bob is 25 years old.

When you leave placeholders empty, the values are replaced in order.

Or, you can give placeholders an explicit positional index and use them in any order you want.

# Access arguments by positional index (explicit)
S = '{1} is {0} years old.'.format(25, 'Bob')

# Prints Bob is 25 years old.

Or, you can refer to your variable substitutions by name.

# Access arguments by name
S = '{name} is {age} years old.'.format(name='Bob', age=25)

# Prints Bob is 25 years old.

Padding and Aligning Strings

You can pad or create space around a value by increasing field size. You can also force the field to be left, right or center-aligned within the available space.

The various alignment options are as follows:

String aligning options
<Align Left
>Align Right (default for numbers).
=Add padding between sign & digits. (valid for numbers only)
^Align Center

Here are some examples:

# Align text left
S = '{:<12}'.format('Left')

# Prints Left        
# Align text right
S = '{:>12}'.format('Right')

# Prints        Right
# Align text center
S = '{:^12}'.format('Center')

# Prints    Center   

By default, the values are padded with whitespace. You can modify that by specifying a fill character.

# Choose custom fill character
S = '{:*^12}'.format('Center')

# Prints ***Center***

Truncate Long Strings

You can truncate long strings by specifying a .precision option.

# Truncate string to two characters
S = '{:.2}'.format('Python')

# Prints Py
# Add padding to a truncated string and align it center
S = '{:^10.2}'.format('Python')

# Prints     Py    

Format Numbers (Integer)

Python provides various type codes to format integers.

Integer formatting type codes
bBinary format
cCorresponding unicode character
dDecimal Integer
oOctal format
xHex format (lowercase letters)
XSame as ‘x’, but uses uppercase letters
nNumber (Same as ‘d’, except it uses current locale setting for number separator)

Here are some examples:

# Convert 42 to hex, octal, binary and unicode character
S = 'int:{0:d}, hex:{0:x}, oct:{0:o}, bin:{0:b}, char:{0:c}'.format(42)

# Prints int:42, hex:2a, oct:52, bin:101010, char:*

If you want to add the prefix ‘0b‘, ‘0o‘, or ‘0x‘ to the output value, specify # format option.

# Add a prefix to Hex, Octal and Binary
S = 'hex:{0:#x}; oct:{0:#o}; bin:{0:#b}'.format(42)

# Prints hex:0x2a; oct:0o52; bin:0b101010

Format Numbers (Floating Points and Decimals)

For floating point numbers, you can achieve a variety of additional formatting effects by specifying left justification, zero padding, numeric signs, total field width, and digits after the decimal point.

Following type codes are used to format floating points and decimal values.

Float formatting type codes
eExponent notation (lowercase)
ESame as ‘e’, but uses uppercase letters
fFloating-point decimal (default precision: 6)
FSame as ‘f’, but uses uppercase letters
gGeneral format. Round numbers (default precision: 6)
GSame as ‘g’ (shows exponent for large numbers)
%Percentage (multiplies by 100 & adds % sign)
# Show floating point number
S = '{:f}'.format(3.141592653)

# Prints 3.141593

Floating point numbers are rounded to 6 decimal digits by default.

If you want to limit the number of digits after the decimal point, specify precision option.

# Specify digits after the decimal point (Precision)
S = '{:.2f}'.format(3.141592653)

# Prints 3.14

To display numbers in scientific (exponential) notation, use type code ‘e‘ or ‘E‘ (for uppercase letter)

# Display numbers with exponent notation
S = '{:.2e}'.format(3141592653)

# Prints 3.14e+09

You can format numbers as percentages using the type code %. It multiplies the number by 100 and displays in floating-point 'f' format, followed by a percent sign.

# Format number as percentage
S = '{:.2%}'.format(19.5/22)

# Prints 88.64%

Format Signed Numbers

Only negative numbers are prefixed with a sign by default. You can change this by specifying the sign format option.

The sign format option is only valid for number types, and can be one of the following:

Number sign formatting options
+Displays sign for both positive and negative numbers
Displays sign only for negative numbers
spaceDisplays space for positive numbers and a minus sign for negative numbers

Here are some examples:

# Display sign for both positive and negative numbers
S = '{:+.2f}, {:+.2f}'.format(3.14, -3.14)

# Prints +3.14, -3.14
# Display sign only for negative numbers
S = '{:-.2f}, {:-.2f}'.format(3.14, -3.14)

# Prints 3.14, -3.14

By default negative numbers are prefixed with a sign, so {:-f} is same as {:f}

When you use ' ' (space) for sign option, it displays a leading space for positive numbers and a minus sign for negative numbers.

# Display a space for positive numbers
S = '{: .2f}, {: .2f}'.format(3.14, -3.14)

# Prints  3.14, -3.14

Padding Numbers (Intergers & Floats)

Similar to strings, you can pad or create space around a number by increasing field width.

# Add padding to a number
S = '{:5d}'.format(42)

# Prints    42

You can add leading zeros to a number by specifying '0' as fill character.

# Padding zeros to a number
S = '{:0>3d}'.format(7)

# Prints 007

For floating points, the padding value represents the length of the complete output (including decimal point & decimal digits).

# Padding zeros to a floating point
S = '{:06.2f}'.format(3.141592653589793)

# Prints 003.14

You can control the position of the sign relative to the padding using = alignment option.

# Padding zeros to a negative number
S = '{:0=8d}'.format(-120)

# Prints -0000120

Thousands Separator and Nibble Separator

The group format option ',', '_' can be used as a thousands separator.

# Using the comma as a thousands separator
S = '{:,}'.format(1234567890)

# Prints 1,234,567,890

For Hex, Octal and Binary numbers, underscore can be used to separate nibbles(every 4 digits).

# Using underscore as a nibble separator
S = '{:_b}'.format(0b01010101010)

# Prints 10_1010_1010

Datetime Formatting

Python allows datetime objects to be formatted inline.

# Using datetime formatting
import datetime
D = datetime.datetime(2010, 7, 4, 12, 15, 58)
S = '{:%Y-%m-%d %H:%M:%S}'.format(D)

# Prints 2010-07-04 12:15:58

Parametrized Formats

Python allows all of the format options to be specified dynamically using parametrization.

# Parametrized fill, alignment and width
S = '{:{fill}{align}{width}}'.format('center', fill='*', align='^', width='12')

# Prints ***center***