# String Formatting
When storing and transforming data for humans to see, string formatting can become very important. Python offers a wide variety of string formatting methods which are outlined in this topic.
# Basics of String Formatting
You can use str.format to format output. Bracket pairs are replaced with arguments in the order in which the arguments are passed:
Indexes can also be specified inside the brackets. The numbers correspond to indexes of the arguments passed to the str.format function (0-based).
Named arguments can be also used:
Object attributes can be referenced when passed into str.format :
Dictionary keys can be used as well:
Same applies to list and tuple indices:
Note: In addition to str.format , Python also provides the modulo operator % —also known as the string formatting or interpolation operator (see PEP 3101
(opens new window) )—for formatting strings. str.format is a successor of % and it offers greater flexibility, for instance by making it easier to carry out multiple substitutions.
In addition to argument indexes, you can also include a format specification inside the curly brackets. This is an expression that follows special rules and must be preceded by a colon ( : ). See the docs
(opens new window) for a full description of format specification. An example of format specification is the alignment directive :
^20 ( ^ stands for center alignment, total width 20, fill with
format allows behaviour not possible with % , for example repetition of arguments:
As format is a function, it can be used as an argument in other functions:
# Alignment and padding
The format() method can be used to change the alignment of the string. You have to do it with a format expression of the form :[fill_char][align_operator][width] where align_operator is one of:
- < forces the field to be left-aligned within width .
- > forces the field to be right-aligned within width .
- ^ forces the field to be centered within width .
- = forces the padding to be placed after the sign (numeric types only).
fill_char (if omitted default is whitespace) is the character used for the padding.
Note: you could achieve the same results using the string functions ljust() , rjust() , center() , zfill() , however these functions are deprecated since version 2.5.
# Format literals (f-string)
Literal format strings were introduced in PEP 498
(opens new window) (Python3.6 and upwards), allowing you to prepend f to the beginning of a string literal to effectively apply .format to it with all variables in the current scope.
This works with more advanced format strings too, including alignment and dot notation.
Note: The f» does not denote a particular type like b» for bytes or u» for unicode in python2. The formating is immediately applied, resulting in a normal stirng.
The format strings can also be nested:
The expressions in an f-string are evaluated in left-to-right order. This is detectable only if the expressions have side effects:
# Float formatting
Same hold for other way of referencing:
Floating point numbers can also be formatted in scientific notation
You can also combine the <0>and
# String formatting with datetime
Any class can configure its own string formatting syntax through the __format__ method. A type in the standard Python library that makes handy use of this is the datetime type, where one can use strftime -like formatting codes directly within str.format :
A full list of list of datetime formatters can be found in the official documenttion
# Named placeholders
Format strings may contain named placeholders that are interpolated using keyword arguments to format .
# Using a dictionary (Python 2.x)
# Using a dictionary (Python 3.2+)
(opens new window) allows to use dictionaries without having to unpack them first. Also the class of data (which might be a custom type) is used instead of a newly filled dict .
# Without a dictionary:
# Format using Getitem and Getattr
Any data structure that supports __getitem__ can have their nested structure formatted:
Object attributes can be accessed using getattr() :
# Formatting Numerical Values
The .format() method can interpret a number in different formats, such as:
Format integers to different bases (hex, oct, binary)
Use formatting to convert an RGB float tuple to a color hex string:
Only integers can be converted:
# Nested formatting
Some formats can take additional parameters, such as the width of the formatted string, or the alignment:
Those can also be provided as parameters to format by nesting more <> inside the <> :
In the latter example, the format string ‘<:<><><>>’ is modified to ‘<:*^15>‘ (i.e. "center and pad with * to total length of 15") before applying it to the actual string ‘foo’ to be formatted that way.
This can be useful in cases when parameters are not known beforehand, for instances when aligning tabular data:
# Padding and truncating strings, combined
Say you want to print variables in a 3 character column.
Note: doubling < and >escapes them.
# Custom formatting for a class
Everything below applies to the `str.format` method, as well as the `format` function. In the text below, the two are interchangeable.
For every value which is passed to the format function, Python looks for a __format__ method for that argument. Your own custom class can therefore have their own __format__ method to determine how the format function will display and format your class and it’s attributes.
This is different than the __str__ method, as in the __format__ method you can take into account the formatting language, including alignment, field width etc, and even (if you wish) implement your own format specifiers, and your own formatting language extensions.1
If your custom class does not have a custom `__format__` method and an instance of the class is passed to the `format` function, **Python2** will always use the return value of the `__str__` method or `__repr__` method to determine what to print (and if neither exist then the default `repr` will be used), and you will need to use the `s` format specifier to format this. With **Python3**, to pass your custom class to the `format` function, you will need define `__format__` method on your custom class.
Syntax
![]()
This example formats two items.
The first item is count. No format-specifier is specified for count. So the value of count is simply inserted in the slot indicated by <0>. The second item is amount and its specifier is 9.6f, which specified the width of the item is 9 and precision is 6. f means a fixed point number. You can use d for decimal integer and s for a string.
For example, the following code
Square boxes above in the image denotes blank space.
Last the number in the last item is rounded up to the specified precision.
If an item requires more spaces than the specified width, the width is automatically increased. For example, in the following code:
displays
Python#111#924.66
The specified width for string item Python is 3, which is smaller than the string size 8. The width is automatically increased to 8. The specified width for int item 111 is 2, which is smaller than its actual size 3. The width is automatically increased to 3. The specified width for float item 924.656 is 3, but it needs width 6 to display 924.66. So the width is automatically increased to 6.
Alignment in str.format()
Single argument formatting
The simplest case while calling the Python format function is to have a single formatter. Below is the syntax to use it.
Description:
- ‘<>’: It is the format target, i.e., the placeholder.
- param: It can be a string, integer, float, or any of the collection types.
- Return: It returns a formatted output with the input argument substituting the placeholder.
Multiple arguments formatting
Multiple arguments formatting
Description:
** ‘<> <>’: We can have multiple placeholders.
** arg1, arg2: They can be a string, integer, float, or any of the collection types.
** Return: It returns a formatted output with the input argument substituting the placeholder.
Output:
By default, strings are left aligned and the numbers are right aligned.
We can put the < or > symbol in the specifier to specify that the item is left or right aligned in the output within the specified field and ^ for the centre-alignment.
For example, the following statements:
displays
Output:
Padding
Padding using the ‘#’ character.
Output:
We can see that the box length for printing the string is 10. It means the max we can accommodate the ten characters. The word “Hello” itself has five letters and the ‘#’ gets filled at the remaining five places.
If you like to align the target string from the left, then use the ‘<‘ symbol.
You can even make a string center-aligned inside a fixed-length box.
print(format(“Hello”, “#6s”))
The carat ‘^’ sign makes the string format to the center.
Format Types
Examples
Formatting a dictionaries in Python using str.format()
The ** indicates that the dictionary should be expanded to a list of keyword parameters. The format method doesn’t take a dictionary as a parameter, but it does take keyword parameters.
That just tells Python that you are providing a dictionary to the function so that it can provide the values in the dictionary, rather than the dictionary itself.
We can do the same when calling any function.
If function ‘f’ takes the args ‘a’,’b’, and ‘c’, you could use
dic = <'a':1,'b':2,'c':3>and call f(**dic)
"I have one <0[fruit]>on the <0[place]>.".format(dic) works too.
dic is the 0th positional argument here and you can access it's keys in the template.
You can format dictionary data using the keyworded arguments.
Formatting a list in Python using str.format()
The Python format method accepts a sequence of positional parameters.If we pass an array or a List, then let’s find out the result.
The whole list gets displayed. We can also decide to print one item from the sequence by providing its index.
We can even send the list item as the positional parameters. To achieve this, we need to unpack it using the * operator.
Примеры работы функции format() в Python
В этой статье мы сосредоточимся на форматировании строки и значений с помощью функции Python format().

Функция Python format() — это встроенная функция String, используемая для форматирования строк.
Функция Python format() function форматирует строки в соответствии с положением. Таким образом, пользователь может изменить положение строки в выводе с помощью функции format().
- <> : Эти фигурные скобки действуют как средство форматирования, и при вызове функции они заменяются строкой, которая должна быть помещена в определенную позицию.
- value : этот параметр может быть строкой, числом или даже целым числом с плавающей запятой. Он представляет собой значение, которое будет заменено средством форматирования в выходных данных.
Форматирование индекса
Функция format() также служит для форматирования строки в определенных пользователем позициях, то есть мы можем изменить положение строки или значения, которое будет помещено в вывод, указав значения индекса внутри фигурных скобок.
В приведенном выше фрагменте кода формат (s1, s2, s4) внутренне присваивает им значения индекса как 0, 1, 2 и т. д. значениям, передаваемым в функцию.
То есть s1 присваивается индексу 0, s2 назначается индексу 1, а s4 присваивается индексу 2.
Таким образом, передав значение индекса строки в <>, мы можем изменить положение строки с помощью значений индекса.
Передача значений аргументам
Мы можем присвоить значения переменным, которые мы хотим отображать внутри списка параметров самой функции.
Заполнение форматированной строки функцией format()
Строки также могут быть отформатированы с точки зрения выравнивания и заполнения.
Передавая конкретное число, оно служит количеством символов, добавляемых в строку.

Передача dict в качестве параметра
Словарь Python также может быть передан в format() как значение для форматирования.
Ключ передается в <>, а функция format() используется для замены ключа его значением соответственно.
Поскольку мы передаем ключи dict в качестве аргументов, чтобы заменить ключи их значениями, нам нужно распаковать словарь. Таким образом, для распаковки словаря используется Python «**» operator .
Передача комплексного числа в качестве аргумента
Данная функция может использоваться для доступа к действительным и мнимым значениям из комплексного числа.
С использованием запятой в качестве значения разделителя
Позволяет нам разделять числовые значения, используя «,» as a separator .
Разделитель, то есть «,» добавляется после трех цифр таким образом, чтобы он работал с разрядами тысяч в системе счисления.
Форматирование чисел
Помимо форматирования числовых значений, можно использовать для представления числовых значений в соответствии с различными системами счисления, такими как двоичная, восьмеричная, шестнадцатеричная и т. д.
Format in Python
Format is the arrangement and representation of something. In Python, we use the format() functions to format our data.
There are two types of format functions in Python, one is the format() function which is used to convert a value to a formatted representation, and the other is the str.format() method used to insert variables in a string without having to concatenate different strings.
Scope of article
- In this article, we'll learn how to format data in Python.
- We'll learn about format() function, str.format() method and the differences between them.
- Everything is explained with the use of examples for easy understanding.
Introduction to format() function in Python
Let us assume, for instance, that you are given some numbers in decimal format and have to convert them into binary, octal, and hexadecimal numbers. Though there are many ways to convert decimal numbers into these formats, the format() function comes in handy here.
The format() is a built-in function in Python that converts a value into the required format/representation (shown in the example below). Code:
Output:
In the above example, we have used the format() function to convert a decimal value into a binary value.
Now we will discuss the syntax and parameters of the format() function.
Syntax of format() in Python
The format() function has two parameters (value and format_spec).
The syntax of the format() function is:
Read the next section to know more about these parameters in detail.
Parameters of format() in Python
The format() function has two parameters:
- value: the value which has to be formatted (value can be a number or a string).
- format_spec (optional): This is a string for inputting the specification of the formatting requirements.
The second parameter (format_spec) is optional; in its absence, the value will be formatted into a string by default.
Format of format specifier (format_spec)
The second parameter of the format() function called format_spec follows a certain format.
At first glance, this may look very intimidating, but this is not as hard as it looks.
Here's an overview of what the various specifiers mean:
fill: (any character)
It is a character that fills up the empty spaces after formatting. It is also called a padding character.
align: It is an option to specify the alignment of the output string.
"<" : left-alignment specifier
">" : right-alignment specifier
"^" : center-alignment specifier
"=" : justified specifier
sign: This determines the use of signs for the output.
"+" : Positive numbers have a "+" sign, and negative numbers have a "-" sign.
" " (space): Positive numbers are preceded by a space, and negative numbers are preceded by a "-" sign.
"#": This specifies that the return value should have a type indication for numbers. For example, hexadecimal numbers should have a "0x" prefix added to them.
"0": This specifies that the output should be sign aware and padded with 0's for consistent output.
width: Specifies the full width of the return value.
",": Specifies that the return value should have commas as a thousand separator.
.precision: Determines the number of characters after the decimal point.
type: This Specifies the output type. The types are three types:
- String: Use an "s" or nothing at all to specify a string.
- Integer: d (decimal), b (binary), o (octal), x (hexadecimal with lowercase characters), X (hexadecimal with uppercase characters), c (character)
- Floating point: f (lowercase fixed point), F (uppercase fixed point), e (exponent using "e" as separator), E (exponent using "E" as separator), g (lowercase general format), G (uppercase general format), % (percentage)
This format is discussed in a detailed manner in the examples section below ("Example 1: Number formatting with format()" and "Example 2: Number formatting with fill, align, sign, width, precision, and type").
Return type of format()
The format() function returns a formatted representation of the given value as per the format specifier. The return value is always a string, irrespective of the input.
Example 1: Number Formatting with format()
Code:
Output:
In the above example, The decimal value is being converted into binary, octal, and hexadecimal values using type specifiers (discussed in the section above — "format of format specifier")
Example 2: Number formatting with fill, align, sign, width, precision, and type
Example: Formatting an Integer Code:
Output:
In the above example, we formatted the integer "4453"; the format_spec is *>+7,d . Let's understand the significance of each symbol in *>+7,d :
- * — The fill character fills up the empty spaces after formatting.
- > — The right align option aligns the output string to the right.
- + — It is a sign option forcing the number to have a sign on its left.
- 7 — It is the width option forcing the number to have a minimum width of 7; empty spaces get filled by fill character.
- , — It is the thousands operator, which puts a comma between all thousands.
- d — It is the type specifier option specifying the number into an integer.
Example: Formatting a floating-point number Code:
Output:
In the above example, we are formatting the floating-point number "933.3629", the format_spec is ^-09.3f . Let's understand the significance of each symbol in ^-09.3f :
- ^ — It is the center align option aligning the output string to the center.
- — — It is a sign option forcing only negative numbers to have a sign.
- 0 — It is a character placed in empty spaces.
- 9 — It is the width option forcing the number to have a minimum width of 9.
- .3 — It is the precision operator specifying the precision of a given decimal number to 3 places.
- f — The type specifier option specifies the number into a floating-point number.
Example 3: Using format() by Overriding __format__()
Code:
Output:
In this example, we have overridden the __format__() method of the class Car .
It now accepts a format parameter and returns Red if it is equal to colour, else None is returned.
The format() function internally runs Car(). __format__("colour") to return Red.
Introduction to String format() Method in Python
There will be multiple instances when we have to insert values in a string, str.format() method is used for this.
Python's str.format() method allows us to format the specified values and insert them in place of placeholders into the string.
The placeholders in the str.format() method are defined using curly brackets "<>". Read more about placeholders in the "Formatters using Positional and Keyword arguments" section below.
Here's an example showing the application of the string format method: Code:
Output:
In the above example, we have used the string format method to insert a value inside a string.
This was just for demonstration; read along to know how this works.
Syntax of String format() method in Python
The str.format() method is required to have one or more than one parameter (values to be formatted and inserted into the string).
Syntax of str.format() method is:
Read the next section to learn about its parameters.
Parameters of String format() method in Python
The str.format() method can have one or more than one parameters, all of which are values that have to be formatted and inserted in the input string.
The values can be of any data type. Parameters can be a list of values separated by commas, a key-value list, or a combination of both.
There are two types of use cases for formatting strings; one is when we have to format/insert only one value into the string, which is called a Single formatter, the other case is when we have to deal with multiple values, called Multiple formatter.
Single Formatter
This means we can pass only one value into the str.format() method, which after getting formatted, takes the placeholder's position inside the string.
Since we are passing only one parameter to the string format method, it is called a single formatter. Let's see how single formatters work:
Code:
Output:
In the above example, we have inserted a single value into the string using the str.format() method where "Everyone likes <>" was the string and "pizza" was the value to be inserted in it in place of the placeholder.
Multiple Formatter
In this case, the string format() method will have more than one parameter.
Multiple formatters are used when we want to insert more than one value in a string. The values substitute the placeholders in order (from left to right). We can use positional arguments to change this order, which we will learn about in the next section.
Here's an example for Multiple formatters:
Code:
Output:
In the above example, we have inserted multiple values into the string using the str.format() method where "People who like <> also like <> with <>" was the string and "pizza", "pasta", and "garlic bread" are values to be inserted in it in place of the placeholder. The three values are inserted into the string in the same order they were passed into the function.
The number of placeholders and values in the format() should be equal. Otherwise, there will be an error.
Formatters Using Positional and Keyword Arguments
The values in the str.format() method are primarily tuple (tuples are a sequence of immutable Python objects) data types. Every value in the tuple is referred to by its indexes starting from 0. These index numbers are then passed into the placeholders, and then they get substituted with the values.
Positional arguments are arguments that refer to the values at a specific index number while calling a function. They can be used to get a particular value in place of the placeholder while formatting strings.
Explained with an example below:
Code:
Output:
In the above example, we are using index numbers in placeholders to refer to the values inside the str.format() method and insert them in the string.
The order of the values inside the sentence can also be changed using indexes.
Explained with an example below:
Code:
Output:
In the above example, we are using index numbers in placeholders to refer to the values inside the str.format() method to change the order of the values being inserted into the string.
Keyword arguments are arguments that can be called by their keys, and by referring to the key, the argument's value can be accessed.
In the String format method, keyword arguments can be used to access the value by putting the key inside the placeholders.
Here is an example of Keyword arguments in the str.format() method:
Code:
Output:
In the above example, we are using keys in placeholders to refer to the keyword arguments in order to access their values and insert them into the string.
Both Keyword arguments and Positional arguments can also be used together.
In this example, we are using both positional and keyword arguments for passing values into the string. The key "food1" passes the value "pizza" into the string in place of the first placeholder, whereas the index number "0" in the second placeholder refers to the first positional argument, which passes the value "pasta" into the string in place of the second placeholder.
Type Specification in format()
Some parameters apart from the index or key can also be enclosed among the curly brackets (placeholders) by using format code syntax. These parameters are used for converting data type, spacing, or aligning, and here we are going to discuss how to convert the data type of values in string format().
Some important conversion types are:
Converting decimal into binary in string format: Code:
Output:
In the above example, we have converted the decimal number (22) into a binary number using a type specifier ("b").
Limiting the number of decimal points in a floating integer: Code:
Output:
In the above example, we are specifying the precision of the floating-point number (43.542130) using the .precision specifier (".3").
Spacing and Alignment Using Formatter
Spacing, aligning or even signs follow the same format of the format_spec discussed above in the section "format of the format specifier".
For alignment, the operators are:
Below are some examples for applying spaces and alignment using str.format(): Code:
Output:
In the above example, we are specifying the width of the first formatted value to be "10", due to which we can see that the string "Delhi" is aligned left to the spaces in the output.
Code:
Output:
In the above example, we are specifying the width of the second formatted value to be "10", due to which we can see that the integer "450" is aligned right to the spaces.
As you can see, the strings are left-justified, and the numbers are right-justified, let's see how to change this behavior using alignment options. Code:
Output:
In the above example, we are specifying the width of the first formatted value to be "10" and left-aligning it using the "<" operator, due to which we can see that the string "Delhi" is aligned left to the spaces.
Code:
Output:
In the above example, we are specifying the width of the second formatted value to be "10" and right-aligning it using the ">" operator, due to which we can see that the string "Delhi" is aligned right to the spaces.
Organizing Data
When handling and displaying data, organizing the data for easy reading, accessing, and management is always preferable. Formatters can help organize the data using align, sign, and width specifiers.
Let's look at a set of unorganized data: Code:
Output:
In the above example, we displayed a data set without organizing it. It's not readable, and numbers are overflowing into each other's columns, making it very hard to distinguish between them.
Now, let's use formatters to organize the same set of data: Code:
Output
In the above example, we have displayed a set of data using align and width specifiers. The alignment is left-align, as seen in the placeholders, this aligns all the sets of columns to the left, and the width is "5", making each column of width "5" to store big values in an organized way.
This is how formatters make data more readable, manageable, accessible, and organized.