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.

Example: Access arguments by default order (implicit)

S = '{} is {} years old.'.format('Bob', 25)
print(S)

Output:

Bob is 25 years old.

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{}

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.

Example: Access arguments by positional index (explicit)

S = '{1} is {0} years old.'.format(25, 'Bob')
print(S)

Output:

Bob is 25 years old.

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{0}

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

Example: Access arguments by name

S = '{name} is {age} years old.'.format(name='Bob', age=25)
print(S)

Output:

Bob is 25 years old.

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{name}

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
OptionMeaning
<Align Left
>Align Right (default for numbers).
=Add padding between sign & digits. (valid for numbers only)
^Align Center

Here are some examples:

Example: Align text left

S = '{:<12}'.format('Left')
print(S)

Output:

Left        

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{:<12}

Example: Align text right

S = '{:>12}'.format('Right')
print(S)

Output:

       Right

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{:>12}

Example: Align text center

S = '{:^12}'.format('Center')
print(S)

Output:

   Center   

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{:^12}

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

Example: Choose custom fill character

S = '{:*^12}'.format('Center')
print(S)

Output:

***Center***

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{:*^12}

Truncate Long Strings

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

Example: Truncate string to two characters

S = '{:.2}'.format('Python')
print(S)

Output:

Py

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{:.2}

Example: Add padding to a truncated string and align it center

S = '{:^10.2}'.format('Python')
print(S)

Output:

    Py    

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{:^10.2}

Format Numbers (Integer)

Python provides various type codes to format integers.

Integer formatting type codes
TypeMeaning
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:

Example: 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)
print(S)

Output:

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

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{0:d,x,o,b,c}

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

Example: Add a prefix to Hex, Octal and Binary

S = 'hex:{0:#x}; oct:{0:#o}; bin:{0:#b}'.format(42)
print(S)

Output:

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

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{0:#x,o,b}

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
TypeMeaning
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)

Example: Show floating point number

S = '{:f}'.format(3.141592653)
print(S)

Output:

3.141593

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{:f}

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.

Example: Specify digits after the decimal point (Precision)

S = '{:.2f}'.format(3.141592653)
print(S)

Output:

3.14

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{:.2f}

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

Example: Display numbers with exponent notation

S = '{:.2e}'.format(3141592653)
print(S)

Output:

3.14e+09

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{:.2e}

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.

Example: Format number as percentage

S = '{:.2%}'.format(19.5/22)
print(S)

Output:

88.64%

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{:.2%}

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
OptionMeaning
+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:

Example: Display sign for both positive and negative numbers

S = '{:+.2f}, {:+.2f}'.format(3.14, -3.14)
print(S)

Output:

+3.14, -3.14

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{:+.2f}

Example: Display sign only for negative numbers

S = '{:-.2f}, {:-.2f}'.format(3.14, -3.14)
print(S)

Output:

3.14, -3.14

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{:-.2f}

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.

Example: Display a space for positive numbers

S = '{: .2f}, {: .2f}'.format(3.14, -3.14)
print(S)

Output:

 3.14, -3.14

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{:' '.2f}

Padding Numbers (Intergers & Floats)

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

Example: Add padding to a number

S = '{:5d}'.format(42)
print(S)

Output:

   42

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{:5d}

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

Example: Padding zeros to a number

S = '{:0>3d}'.format(7)
print(S)

Output:

007

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{:0>3d}

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

Example: Padding zeros to a floating point

S = '{:06.2f}'.format(3.141592653589793)
print(S)

Output:

003.14

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{:06.2d}

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

Example: Padding zeros to a negative number

S = '{:0=8d}'.format(-120)
print(S)

Output:

-0000120

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{:0=8d}

Thousands Separator and Nibble Separator

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

Example: Using the comma as a thousands separator

S = '{:,}'.format(1234567890)
print(S)

Output:

1,234,567,890

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{:,}

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

Example: Using underscore as a nibble separator

S = '{:_b}'.format(0b01010101010)
print(S)

Output:

10_1010_1010

Explanation:

{field:fillalignsign#widthgroup.precisiontype}
{:_b}

Datetime Formatting

Python allows datetime objects to be formatted inline.

Example: Using datetime formatting

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

Output:

2010-07-04 12:15:58

Parametrized Formats

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

Example: Parametrized fill, alignment and width

S = '{:{fill}{align}{width}}'.format('center', fill='*', align='^', width='12')
print(S)

Output:

***center***