A Complete Guide to Format Specifiers in Python

Sahil Jain
4 min readMar 18, 2021

--

Syntax

s.format(item0, item1, item2, ..., itemk)

where,
s: string object that may consist of substrings and formatting instruction for each item in the form of {index:format-specifier}
index: refers to the item
format-specifier: specifies how the item is formatted

Example code:

count = 5 
amount = 45.56
print("count is {0} and amount is {1:9.6f}".format(count, amount))

Displays:
count is 5 and amount is 45.560000

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

print("{0:8s}{1:8d}{2:8.1f}".format("Python", 1234, 5.68))
Memory-Space alignment in format specifier

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:

print("{0:3s}#{1:2d}#{2:3.2f}".format("Python", 111, 924.656))

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.

'{}'.format('Formatting a String in Python')

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

'{} {}'.format(arg1, arg2)

Multiple arguments formatting

'{} {}'.format(arg1, arg2)

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.

‘{},{}’.format(“Python”, “Format”)

Output:

'Python,Format'

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:

print("{0:>8d}#{1:>8s}#{2:>8.1f}".format(1234,"Python",5.63))
print("{0:<8d}#{1:<8s}#{2:<8.1f}".format(1234,"Python",5.63))
print("{0:>8d}#{1:<8s}#{2:>8.1f}".format(1234,"Python",5.63))

displays

print("{0:>8}#{1:>8}#{2:>8.1f}".format(1234, "Python", 5.63)) 
print("{0:<8}#{1:<8}#{2:<8.1f}".format(1234, "Python", 5.63))
print("{0:8}#{1:8}#{2:8.1f}".format(1234, "Python", 5.63))

Output:

1234#  Python#     5.6
1234 #Python #5.6
1234#Python # 5.6

Padding

Padding using the ‘#’ character.

print(format("Hello", "#>10s"))

Output:

#####Hello

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.

print(format("Hello", "#<10s"))
Hello#####

You can even make a string center-aligned inside a fixed-length box.
print(format(“Hello”, “#6s”))

Output:

Hello#

The carat ‘^’ sign makes the string format to the center.

Format Types

 d   :   decimal
s : string
f : fixed-point/floating
b : binary
o : octal
x : hex
g : general
e : scientific

Examples

print("{0:b}".format(10))Output:
1010
print("{0:o}".format(10))
Output:
12
print("{0:x}".format(10))
Output:
a
print("{0:d}".format(10))
Output:
10
print("{0:s}".format("Hello"))
Output:
Hello
print("{0:g}".format(10))
Output:
10
print("{0:g}".format("Hello"))---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-55-2ac6ab4a836a> in <module>()
----> 1 print("{0:g}".format("Hello"))
ValueError: Unknown format code 'g' for object of type 'str'print("{0:3.2f}".format(9999.456))
Output:
9999.46
print("{0:#<8.2f}".format(99))
Output:
99.00###
print("{0:e}".format(9999.456))
Output:
9.999456e+03

Formatting a dictionaries in Python using str.format()

dic = {'fruit':'apple', 'place':'table'}
dic
Output:
{'fruit': 'apple', 'place': 'table'}
print("I have one {fruit} on the {place},".format(**dic))
Output:
I have one apple on the table,

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)

print("I have one {0[fruit]} on the {0[place]}.".format(dic))Output:
I have one apple on the table.

"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.

print("Jake's salary is {Sal[Jake]}\nAnand's salary is {Sal[Anand]}".format(Sal={'Jake':'$100k','Anand':'$110k'}))
Output:
Jake's salary is $100k
Anand's salary is $110k

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.

langs = ['C','C++','Python']
print("SkillSet: {}".format(langs))
SkillSet: ['C', 'C++', 'Python']

The whole list gets displayed. We can also decide to print one item from the sequence by providing its index.

print("SkillSet: {[1]}".format(langs))
#or
print("SkillSet: {0[1]}".format(langs))
Output:
SkillSet: C++
SkillSet: C++

We can even send the list item as the positional parameters. To achieve this, we need to unpack it using the * operator.

print("SkillSet: {}".format(*langs))
Output:
SkillSet: C

--

--