Python - String Formatting Best Practices (%, str formatting, f-stirng)

I have summarized Python String formatting.

There are a few ways to format strings:

  • % formatting: old-style formatting
  • String formatting: A new style of formatting
  • f-string: A new style of formatting available in Python 3.6 and later.

Let`s see how to apply each of the three methods above to the same string.

basic format

This is the default format. % formatting, String formatting, and f-string in that order.

temperature = 202
measure = 'Fahrenheit'
print('Water boils at %d degrees %s' % (temperature, measure))     # 1
print('Water boils at {} degrees {}'.format(temperature, measure)) # 2
print(f'Water boils at {temperature} degrees {measure}')           # 3
  1. You can use like C style.
  2. You can pass an argument to format().
  3. It is similar to the formatting styles supported by modern languages. If you type f before the string,f-string is applied. It is easy to read because variables are entered directly in {}.

result

Water boils at 202 degrees Fahrenheit
Water boils at 202 degrees Fahrenheit
Water boils at 202 degrees Fahrenheit

Padding, Aligning

Padding is on the left and strings on the right.

string = 'test'
print('%10s' % (string))
print('{:>10}'.format(string))
print(f'{string:>10}')

If you look at the result, the string is right aligned. Six spaces, except four strings, in ten spaces were placed on the left.

      test
      test
      test

Contrary to the above, Padding is on the right and strings on the left. (In String formatting andf-string, you can type < after < or omit it.)

string = 'test'
print('%-10s' % (string))
print('{:10}'.format(string))
print(f'{string:10}')

result

test      
test      
test      

Padding with specific characters instead of padding with spaces. Instead of *, you can change it to any character you like.

string = 'test'
print('{:*>10}'.format('test'))
print(f'{string:*>10}')

print('{:*<10}'.format('test'))
print(f'{string:*<10}')

result

******test
******test
test******
test******

This is how you align strings with centered. Use ^.

string = 'test'
print('{:^10}'.format('test'))
print(f'{string:^10}')

print('{:*^10}'.format('test'))
print(f'{string:*^10}')

result

   test   
   test   
***test***
***test***

Truncate string

This example truncates strings to 5 characters.

string = 'xylophone'
print('%-.5s' % (string))
print('{:.5}'.format(string))
print(f'{string:.5}')

result

xylop
xylop
xylop

number output

This is an example of outputting as a float. float only represents 6 decimal places.

number = 3.141592653589793
print('%f' % (number))
print('{:f}'.format(number))
print(f'{number:f}'.format(number))

print(f'{number}')

result

3.141593
3.141593
3.141593
3.141592653589793

The following example outputs only two digits after the decimal point:

number = 3.141592653589793
print('%.2f' % (number))
print('{:.2f}'.format(number))
print(f'{number:.2f}')

result

3.14
3.14
3.14

The following example shows how to print only two digits after the padding and the decimal point. The meaning of 08 is that 8 characters are output and the remaining space is filled with 0.

number = 3.141592653589793
print('%08.2f' % (number))
print('{:08.2f}'.format(number))
print(f'{number:08.2f}')

result

00003.14
00003.14
00003.14

The following example shows padding applied to an Integer.

number = 12
print('%04d' % (number))
print('{:04d}'.format(number))
print(f'{number:04d}')

result

0012
0012
0012

The following is similar to the example above, but prints a positive + together.

number = 12
print('%+04d' % (number))
print('{:+04d}'.format(number))
print(f'{number:+04d}')

result

+012
+012
+012

str, repr formatting

This example prints the __str__ and__repr__ of the object to the string in various ways.

class Comedian:
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    def __str__(self):
        return f"{self.first_name} {self.last_name} is {self.age}."

    def __repr__(self):
        return f"{self.first_name} {self.last_name} is {self.age}. Surprise!"

new_comedian = Comedian("Eric", "Idle", "74")
print("%s" % (new_comedian))
print("%r" % (new_comedian))

print("{0!s}".format(new_comedian))
print("{0!r}".format(new_comedian))

print(f'{new_comedian}')
print(f'{new_comedian!r}')

result

Eric Idle is 74.
Eric Idle is 74. Surprise!
Eric Idle is 74.
Eric Idle is 74. Surprise!
Eric Idle is 74.
Eric Idle is 74. Surprise!

Named placeholders

An example of applying an object to formatting using keywords.

data = {'first': 'Hodor', 'last': 'Hodor!'}
print('%(first)s %(last)s' % data)
print('{first} {last}'.format(**data))

result

Hodor Hodor!
Hodor Hodor!

For String formatting, inPython 3.2 and above, you can use like this. The result is the same as above.

print('{first} {last}'.format_map(data))

Get item, Get attribute

In the case of f-string, the string must be expressed as "(double quote) because '(single quote) is used when entering the key of the map internally (or vice versa).

person = {'first': 'Jean-Luc', 'last': 'Picard'}
print('{p[first]} {p[last]}'.format(p=person))
print(f"{person['first']} {person['last']}")

result

Jean-Luc Picard
Jean-Luc Picard

Here is an example for an array:

data = [4, 8, 15, 16, 23, 42]
print('{d[4]} {d[5]}'.format(d=data))
print(f'{data[4]} {data[5]}')

result

23 42
23 42

Here is an example for a class:

class Plant(object):
    type = 'tree'
    kinds = [{'name': 'oak'}, {'name': 'maple'}]

print('{p.type}: {p.kinds[0][name]}'.format(p=Plant()))

p = Plant()
print(f"{p.type}: {p.kinds[0]['name']}")

result

tree: oak
tree: oak

Datetime

Here is an example for datetime

from datetime import datetime
print('{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5)))

date = datetime(2001, 2, 3, 4, 5)
print(f"{date:%Y-%m-%d %H:%M}")

result

2001-02-03 04:05
2001-02-03 04:05

Parameterized format

You can apply formatting by passing a value as an argument.

The following example applies the aligning and padding introduced above.

p_align = '^'
p_width = '10'
string = 'test'
print('{:{align}{width}}'.format(string, align=p_align, width=p_width))
print(f'{string:{p_align}{p_width}}')

result

   test   
   test   

Here is an example for datetime.

from datetime import datetime
dt = datetime(2001, 2, 3, 4, 5)
print('{:{dfmt} {tfmt}}'.format(dt, dfmt='%Y-%m-%d', tfmt='%H:%M'))
print(f'{dt:{"%Y-%m-%d"} {"%H:%M"}}')

result

2001-02-03 04:05
2001-02-03 04:05

Reference

codechachaCopyright ©2019 codechacha