The world’s leading publication for data science, AI, and ML professionals.

Discovering All the Charms in Python3 String Format Function

A magic function formats Python strings that gives you more ideas in presenting strings and number.

Photo by Chris Ried on Unsplash
Photo by Chris Ried on Unsplash

Since Python3 involves the [str.Format()](https://docs.python.org/3.8/library/stdtypes.html#str.format) function, we have a more elegant way to define string templates and insert our variable values as arguments in this function.

This article lists all the different ways of using this function, as well as showing the potentials that we can do with it.

0x01 Passing arguments by position

We need to use curly braces {} as a placeholder, and then pass the arguments from the format function into the string template. There are many ways of using such a technique, which are listed as follows.

If we don’t specify the position, the arguments will be passed in default order.

>>> '{} {} {}'.format('I', 'love', 'Python')
'I love Python'

We can also define the position and implement the same thing.

>>> '{0} {1} {2}'.format('I', 'love', 'Python')
'I love Python'

In the string template, we can customise the positions.

>>> '{1} {0} {2}'.format('love', 'I', 'Python')
'I love Python'

If there are more arguments in theformat function than they are defined in the string template, then the extra arguments will be ignored.

>>> '{0} {1} {2}'.format('I', 'love', 'Python', 'yes')
'I love Python'

We can also use the argument at particular positions multiple times in the string template. Of course, using format function this way requires the position explicitly specified.

>>> '{0} {1} {2}. {3} {1}s {2}, too'.format('I', 'love', 'Python', 'She')
'I love Python. She loves Python, too'

0x02 Passing arguments by key

Compare to a position number, a key that is defined using text would give more readability to your code. So, sometimes you may want to pass the arguments by key.

>>> '{subject} {verb} {object}'.format(subject='I', verb='love', object='Python')
'I love Python'

0x03 Passing a dictionary

Rather than using "key=value" pairs inside the format function, we can directly pass a dictionary in, since it is also a "key: value" format.

>>> dict = {'subject': 'I', 'verb': 'love', 'object': 'Python'}
>>> '{subject} {verb} {object}'.format(**dict)
'I love Python'

0x04 Passing a list

You don’t have to extract values from a list before you can pass it into a string template using a format function.

>>> l = ['I', 'love', 'Python']
>>> '{0} {1} {2}'.format(*l)
'I love Python'

You can also access the elements in a list by subscripts.

>>> l = ['I', 'love', 'Python']
>>> '{0[0]} {0[1]} {0[2]}'.format(l)
'I love Python'

Advanced Usage: Formatting Symbols

In the curly braces {}, we can insert not only the position indicators but also formatting symbols. The available formatting symbols are shown in the table below.

The table above is printed completely using format function, the source code is as follows.

def table():
 print('|| {:=^15} || {:=^50} ||'.format(' symbols ', ' meanings '))
 print('|| {:<15} || {:<50} ||'.format(':', 'format indicator'))
 print('|| {:<15} || {:<50} ||'.format('-/=#', 'filling characters'))
 print('|| {:<15} || {:<50} ||'.format('<', 'left aligned'))
 print('|| {:<15} || {:<50} ||'.format('>', 'right aligned'))
 print('|| {:<15} || {:<50} ||'.format('^', 'centre aligned'))
 print('|| {:<15} || {:<50} ||'.format('10 (number)', 'width'))
 print('|| {:<15} || {:<50} ||'.format(',', 'formating number'))
 print('|| {:<15} || {:<50} ||'.format('.', 'decimal precision'))
 print('|| {:<15} || {:<50} ||'.format('f', 'floating number indicator'))
 print('|| {:<15} || {:<50} ||'.format('b', 'binary number'))
 print('|| {:<15} || {:<50} ||'.format('d', 'decimal number'))
 print('|| {:<15} || {:<50} ||'.format('o', 'octal number'))
 print('|| {:<15} || {:<50} ||'.format('x', 'hex number'))
 print('|| {0:=^15} || {0:=^50} ||'.format(''))

These formatting symbols will be explained in the next section.


0x05 Filling, alignment and width

The alignment and width must be used together. The former must be either< for left-aligned, > right-aligned or ^ for central-aligned, while the latter must be an integer.

>>> print('|{:<15}|'.format('left'))
|left           |
>>> print('|{:^15}|'.format('centre'))
|    centre     |
>>> print('|{:>15}|'.format('right'))
|          right|

If a filling character is provided, all the spaces in the strings above will be replaced by the given character.

>>> print('|{:=<15}|'.format('left'))
|left===========|
>>> print('|{:*^15}|'.format('centre'))
|****centre*****|
>>> print('|{:$>15}|'.format('right'))
|$$$$$$$$$$right|

Please note that the filling character can be anything, but must be only one character.

0x06 Decimal precision

The format function also allows us to specify the precision of a decimal number.

>>> print('{:.3f}'.format(3.1415926))
3.142

We can even directly show a percentage from a calculation

>>> print('{:.2%}'.format(7/8))
87.50%

0x07 Number formatting

I found that the number formatting feature of format function is quite useful. It can easily add commas at the correct position.

>>> print('{:,}'.format(123456789))
123,456,789

In addition, we can control the output format for positive and negative numbers in order to have better presentations.

Always show the sign:

>>> print('{:+f}n{:+f}'.format(100, -100))
+100.000000
-100.000000

Add a space to positive numbers so that the number starts at the same position as the negative numbers:

>>> print('{: f}n{: f}'.format(100, -100))
 100.000000
-100.000000

0x08 Number base conversion

We can also use format function to convert the base of numbers quickly.

Decimal to binary:

>>> print('{:b}'.format(100))
1100100

Binary to decimal

>>> print('{:d}'.format(0b1100100))
100

Decimal to octal

>>> print('{:o}'.format(100))
144

Decimal to hex

>>> print('{:x}'.format(100))
64

0x09 Directly convert datetime to string

Usually, we need to use strftime function to convert a datetime object to string type with a specific format. However, if you only want to print the datetime, you don’t have to use that function.

>>> from datetime import datetime
>>> print('{:%d-%B,%Y %A %H:%M:%S}'.format(datetime.now()))
11-March,2020 Wednesday 22:17:44

Summary

Photo by Nils Stahl on Unsplash
Photo by Nils Stahl on Unsplash

Here is all the magic of str.format() function in Python. I hope this gives you more ideas when you are printing or formatting your Python strings and numbers.

Join Medium with my referral link – Christopher Tao

If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)


Related Articles