English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Usage and examples of the format() method of Python strings

Python String Methods

The format() method of the string formats the specified values and inserts them into the placeholders of the string.
Placeholders are defined using curly braces {}. More information about placeholders can be found in the 'Placeholders' section below.
The format() method returns a formatted string.

The syntax of the format() method is:

template.format(p0, p1, ..., k0=v0, k1=v1, ...)

Here, p0, p1,...are respectively positional parameters and k0, k1,...has value keyword parameters v0, v1,...。

And, the template is a mixture of format codes and parameter placeholders.

string format() parameters

The format() method takes an arbitrary number of parameters. However, they are divided into two types of parameters:

  • positional parameters -which can be accessed using the parameter index in the curly braces {index}

  • keyword parameters -A parameter list of the type key=value, which can be accessed using the parameter key in the curly braces {key}

The return value of the string format()

The format() method returns a formatted string.

How does the string format() work?

format() reads the types of the parameters passed to it and formats them according to the format codes defined in the string.

for positional parameters

Here, parameter 0 is the string "Adam", parameter1is a floating-point number230.2346.

Note: In Python, the parameter list starts from 0.

The string "Hello {0}, your balance is {1:9.3f}" is the template string. It contains format codes used for formatting.

curly braces are just placeholders for the parameters to be placed. In the above example, {0} is the placeholder for "Adam", {1:9.3f} is230.2346are placeholders.

Since template string references format() parameters such as {0} and {1}, so these parameters are positional parameters. They can also be referenced without numbers, because {} and Python internally convert them to numbers.

Internally,

  • Since "Adam" is the 0 isparameter, so it is placed at the {0} position. Since {0} does not contain any other format codes, it does not perform any other operations.

  • However, the first parameter230.2346is not like that. Here, {1:9.3f} will230.2346is placed in its position and executed9.3f operation.

  • f specifies the format is processing floating-point numbers. If not specified correctly, it will generate an error.

  • before the ".". (9specifies the number (230.2346is the minimum width that can be adopted (/padding. In this case,230.2346is allocated at least9positions, including ".".
    If the alignment option is not specified, it is aligned to the right of the remaining spaces. (For strings, it is left-aligned.)

  • after the ".". (3is truncated to the decimal part (2346is truncated to the specified number. In this case,3346is truncated after2346.
    the remaining numbers (46will be rounded and output235.

For keyword parameters

We use the same example above to demonstrate the difference between keyword and positional parameters.

Here, we not only use parameters, but also use key-value pairs as parameters. That is, name="Adam" and blc=230.2346.

Since these parameters are identified by their keys as {name} and {blc}9.3f} referenced, so they are called keyword or named parameters.

Internally,

  • placeholder {name} is replaced with the value of name-"Adam". Since it does not contain any other format codes, it placed "Adam".

  • For parameter blc = 230.2346, placeholder {blc:9.3f} will be replaced with the value230.2346. But before replacing it, it performs9.3f operation.
    output230.235. The decimal part is in3is truncated, and the rest of the digits are rounded. Similarly, the total width is allocated9, leaving two spaces on the left.

Basic format using format()

The format() method allows the use of simple placeholders for formatting.

Example1: Basic format for default, positional, and keyword parameters

# Default parameters
print("Hello {}, your balance is {}.".format("Adam", 230.2346))
# Positional parameters
print("Hello {0}, your balance is {1}.".format("Adam", 230.2346))
# Keyword parameters
print("Hello {name}, your balance is {blc}.".format(name="Adam", blc=230.2346))
# Mixed parameters
print("Hello {0}, your balance is {blc}.".format("Adam", blc=230.2346))

All output will be the same when running the program:

Hello Adam, your balance is 230.2346.
Hello Adam, your balance is 230.2346.
Hello Adam, your balance is 230.2346.
Hello Adam, your balance is 230.2346.

Note:For mixed parameters, keyword arguments must always follow positional arguments.

Use format() to format numbers

You can use the format specifiers given below to set the number format:

Number format type
TypeMeaning
dDecimal integer
cCorresponding Unicode character
bBinary format
oOctal format
xHexadecimal format (lowercase)
XHexadecimal format (uppercase)
nSame as 'd'. Besides, the current language environment settings for number separators are used.
eExponential notation (lowercase e)
EExponential symbol (uppercase E)
fDisplay fixed-point notation (default value:6)
FSame as 'f'. Besides, 'inf' is displayed as 'INF' and 'nan' as 'NAN'.
gGeneral format. Round the number to p significant digits. (Default precision:6)
GSame as 'g'. Switch to 'E' if the number is very large.
%Percentage. Multiply by100 and ends with %.

Example2: Simple number format

# Integer parameters
print("Number: :={0:d}".format(123))
# Floating-point parameters
print("Floating-point number: :={0:f}".format(123.4567898))
# Octal, binary, and hexadecimal formatting
print("bin: :={0:b}, oct: :={0:o}, hex: :={0:x}".format(12))

When you run the program, the output will be:

Numbers: 123
Floating-point numbers:123.456790
bin: 1100, oct: 14, hex: c

Example3# Number formatting with int and float

# Integer with minimum width
print("{:5d}".format(12))
# Width does not work for numbers longer than padding
print("{:2d}".format(1234))
# Padding for floating-point numbers
print("{:8.3f}".format(12.2346))
# Integer with minimum width of 0
print("{:=05d}".format(12))
# Floating-point numbers filled with zeros
print("{:=08.3f}".format(12.2346))

When you run the program, the output will be:

   121234  12.235000120012.235

Here,

  • In the first statement, {:5d} takes an integer parameter and specifies the minimum width5. Since the alignment method was not specified, it is right-aligned.

  • In the second statement, you can see the width (2)is less than the number (1234),therefore it does not need to leave any space on the left and will not truncate the number.

  • Unlike integers, floating-point numbers have both an integer and a fractional part. And, the minimum width defined for this number includes both parts, including the ".".

  • In the third statement, {:8.3f} truncates the decimal part to3digits, rounding the last two digits. And, the number is now12.235The entire width is8Retained on the left2positions.

  • If you want to fill the remaining positions with zeros, place a zero before the format specifier. It applies to integers and floating-point numbers: {:05d} and {:08.3f}.

Example4# Formatting for signed numbers

# Display+number sign
print("{:+f} :=:+f}".format(12.23, -12.23))
# Only display-number sign
print("{:-f} :=:-f}".format(12.23, -12.23))
# Display+spaces with the number sign
print("{:=f} :=f".format(12.23, -12.23))

When you run the program, the output will be:

+12.230000 -12.230000
12.230000 -12.230000 12.230000 -12.230000

Number alignment formatting

When specifying a certain width for numbers, the operators < and and are used for alignment. ^>=

Number alignment formatting
TypeMeaning
<Left-aligned remaining space
^Center-aligned remaining space
>aligned to the right with the remaining space
=Aligning the signed (+)(-)force to the left

Example5# Left-aligned, right-aligned, and centered number formatting

# Right-aligned integers
print("{:5d}".format(12))
# Floating-point numbers with center alignment
print("{:^10.3f}".format(12.2346))
# Integer left-aligned, filled with 0
print("{:<05d}".format(12))
# Center-aligned floating-point numbers
print("{:=8.3f}".format(-12.2346))

When you run the program, the output will be:

   12  12.235  12000- 12.235

Note:For the third example, left-aligned zero-padding for integers may cause issues, and the example returns12000 instead of12.

String formatting using format()

As a number, you can format strings in a similar way using format().

Example6# String formatting with padding and alignment

# Left-aligned string padding
print("{:5).format("cat")
# Right-aligned string padding
print("{:>}})5).format("cat")
# Center-aligned string padding
print("{:^5).format("cat")
# Center-aligned string padding
# And '*' Padding character
print("{:*^5).format("cat")

When you run the program, the output will be:

cat cat cat *cat*

Example7Using format() to truncate strings

# Truncate the string to3letters
print("{:.3).format("caterpillar")
# Truncate the string to3letters
# And padding
print("{:5.3).format("caterpillar")
# Truncate the string to3letters,
# Padding and center alignment
print("{:^5.3).format("caterpillar")

When you run the program, the output will be:

catcat cat

Using format() to format class and dictionary members

Python's built-in getattr() is used for class members in the form of “.age”. And it uses __getitem__() to find dictionary members in the form of “[index]”.

Example8Using format() to format class members

# Define Person class
class Person:
    age = 23
    name = "Adam"
# Formatting age
print("{p.name}'s age is: {p.age}".format(p=Person()))

When you run the program, the output will be:

Adam's age is: 23

Here, the Person object is passed as a keyword argument p.

In the template string, access the Person's name and age with .name and .age.

Example9Using format() to format dictionary members

# Define Person dictionary
person = {'age': 23, 'name': 'Adam'}
# Formatting age
print("{p[name]}'s age is: {p[age]}".format(p=person))

When you run the program, the output will be:

Adam's age is: 23

Similar to class, the person dictionary is passed as a keyword argument p.

In the template string, access the person's name and age with [name] and [age].

There is a simpler way to use Python to format dictionary str.format(**mapping).

# Define Person dictionary
person = {'age': 23, 'name': 'Adam'}
# Formatting age
print("{name}'s age is: {age}".format(**person))

** Is the format parameter (minimum field width).

Using format() as a parameter for format codes

You can also pass format codes dynamically, such as precision, alignment, and fill characters as positional or keyword arguments.

Example10Using dynamic formatting with format()

Dynamic String Formatting Template
string = "{:{fill}{align}{width}}"

print(string.format('cat', fill='*, align='^', width=5))
# Dynamic floating-point format template
num = "{:\{align\}\{width\}\.\{precision\}f}"

print(num.format(123.236, align='<' width=8, precision=2))

The output when running the program is:

**cat**123.24

Here,

  • In the first example, "cat" is the formatted positional argument. Similarly, fill='*'align='^' and width=5are keyword arguments.

  • In the template string, these keyword parameters are not as ordinary strings to be printed but as actual format codes retrieved, fill, align, and width.
    the parameters will replace the corresponding named placeholders, and the string "cat" will be formatted accordingly.

  • Similarly, in the second example,123.236are positional arguments, and align, width, and precision are passed to the template string as format codes.

Other format options with format()

format() also supports specific type formatting options, such as date and time formats and complex number formats.

format() internally calls __format__() from datetime, while format() accesses the properties of complex numbers.

You can easily overwrite the __format__() method of any object for custom formatting.

Example11: Use format() and the specific type formatting by rewriting __format__() method

import datetime
# Date and time format
date = datetime.datetime.now()
print("Current time: \{%Y/\%m/\{%d \%H:\%M:\%S\}".format(date))
# Complex number format
complexNumber = 1+2j
print("Real part: \{0.real\} and Imaginary part: \{0.imag\}".format(complexNumber))
# Custom __format__() method
class Person:
    def __format__(self, format):
        if(format == 'age'):
            return ''23"
        return 'None'
print("Adam's age is: \{:\age\}".format(Person()))

The output when running the program is:

Current time: 2020/04/17 14:33:02
Real part: 1.0 and Imaginary part: 2.0
Adam's age is: 23

Here,

  • For datetime:
    The current date and time are passed as positional arguments to the format() method.
    And internally using the __format__() method, format() can access year, month, day, hour, minute, and second.

  • For complex numbers:
    1 + 2j is internally converted to a ComplexNumber object.
    Then access its properties real and imag, the number is formatted.

  • Overwrite __format__():
    Like datetime, you can overwrite your own __format__() method for custom formatting, and when accessed with {age}, the format will return the age

You can also use the __str__() and __repr__() functions of the object by using the abbreviated notation of format().

Like __format__(), you can easily overwrite the __str__() and __repr__() methods of the object.

Example12: Use the abbreviated __str__() and __repr__() of format() as !r and !s

# __str__() and __repr__() abbreviated as !r and !s
print("Quotes: {0!r}, Without Quotes: {0!s}".format("cat"))
# __str__() and __repr__() implementation of the class
class Person:
    def __str__(self):
        return "STR"
    def __repr__(self):
        return "REPR"
print("repr: {p!r}, str: {p!s}".format(p=Person()))

The output when running the program is:

Quotes: 'cat', Without Quotes: cat
repr: REPR, str: STR

Python String Methods