String Formatting

Often formatting of strings is related to their output on the screen. However, it should be remembered that a ready-formed string is passed to the output. Creating a string, that is inserting data into it in the specified formats, is a separate operation. The finished string can, for example, be assigned to a variable, rather than displayed immediately on the screen.

% - the string formatting operator

For strings, the % operator performs a formatting and pasting operation so that the object to its right is embedded according to certain rules in the string to its left:

string % value

This formatting method is considered old because it is borrowed from the printf function of the C language, but in Python other ways to insert data into "template strings" appeared in addition to it. However, in some cases it is more convenient to use the % operator.

Output of a float number with a given precision

The division operator / returns a float. If the number of decimal places is infinite, Python will print it with more decimal places.:

a = 4 / 3
print(a)
1.3333333333333333

You can use the string formatting operator (%) to round a number to the required precision. For example, you need to leave only two decimal places. To do this, inside the string, that is in quotes, write a combination of characters that begins with the sign %. Next, put a point. The numeric after the dot indicates the number of decimal places. The symbol f denotes the data type float.

a = 4 / 3
print('%.2f' % a)
1.33

Note that the variable a contains a float with a large number of decimal places. The string '1.33' is the result of the expression '%.2f' % a. The print() function is passed the ready string '1.33'. Before it, this string could be assigned to a separate variable:

a = 4 / 3
b = '%.2f' % a
print(b)

On the other hand, it is not necessary to specify a variable on the right side of the string formatting operator. More often the expression is written here. It is placed in parentheses.

print('%.2f' % (4 / 3))
1.33

A string containing conversion specifiers can also contain common characters:

print('A = %.1f, B = %d' % (3, 4))
A = 3.0, B = 4

The d character in insertion format denotes an integer (int type).

The string formatting operator performs rounding of real numbers, rather than simply discarding "extra" digits:

print('%.2f, %.2f' % (0.123, 0.126))
0.12, 0.13

Character output

To get any character from the Unicode table, the letter c is used in the specifier, and the code of the required character is indicated after the formatting operator sign.

print('%c' % 189)
print('%c' % 32400)
½
纐

Inserting values through dictionary keys

ab = {'good': 'AB', 'price': 2.3, 'qty': 8}
print('%(good)s, %(price).2f' % ab)
AB, 2.30

Data outputting in fields of a given width

Sometimes the data needs to be displayed in the form of a table. This means that each data element is displayed in a field of a certain width, which is measured in character spaces.

For example, instead of something like this:

First 483 1.1
Second 9 10.7

we need to get this:

First     483      1.1
Second      9     10.7

For such cases, in the format of inserting a data element into a string, the field width (number of character spaces) is indicated. This is done immediately after the percent sign.

print('%-7s %5d %8.1f' % ('First', 483, 1.1))
print('%-7s %5d %8.1f' % ('Second', 9, 10.65))

The minus sign causes the data to be left justified. They are right-aligned by default:

print('%7s %5d' % ('First', 483))
print('%7s %5d' % ('Second', 9))
  First   483
 Second     9

The format method of the str type

The format string method inserts the arguments passed to it into a string it is applied to. In a string, insertion places, or "replacement fields", are defined by curly braces. Braces can contain indexes or keys of arguments passed to the format method.

print("{}, {} and {}".format('A', 8, 'B'))
print("{1}, {0} and {2}".format('A', 8, 'B'))
A, 8 and B
8, A and B

More arguments can be passed to format() than there are insertion points in the string. In this case, the remaining arguments are ignored.

nums = ['I', 'II', 'III', 'IV', 'V']
print("{} {} {}".format(*nums))
print("{0} {4}".format(*nums))
I II III
I V

Using keys to insert values:

print('{var} = {value}'.format(var='pi', value=3.14))
pi = 3.14
u = {'name': 'Bob','age': 35}
print('{name}-{age}'.format(**u))
print('{name}'.format(**u))
print('{0}-{age}'.format('John', **u))
Bob-35
Bob
John-35

Displaying object attributes:

class House:
    size = 5
    street = "Red"


h = House()
print('{0.size}, {0.street}'.format(h))
5, Red

The format method allows you to set the field width and alignment:

u = {'name': 'Bob','age': 35}
print('{name:10}-{age:4}-'.format(**u))
print('{name:>10}-{age:>4}-'.format(**u))
print('{name:^10}-{age:^4}-'.format(**u))
Bob       -  35-
       Bob-  35-
   Bob    - 35 -

Outputting of real numbers:

print('{}'.format(4/3))
print('{0:f}'.format(4/3))
print('{:.2f}'.format(4/3))
print('{0:10.2f}'.format(4/3))
print('{0:e}'.format(4/3))
1.3333333333333333
1.333333
1.33
      1.33
1.333333e+00

Formatted string literals

Recent versions of Python have introduced the ability to use so-called formatted string literals. Unlike common string literals, f-strings are preceded by the letter f.

The string can contain inclusions in braces. During program execution, the interpreter executes expressions in braces, inserting their result into the appropriate places of the string.

user = input()
print(f'Hello {user}!')

a = 4.5678
print(f'Result {a:5.2f}')
Bob
Hello Bob!
Result  4.57
print(f'Hello {input()}!')

a = 4
b = 3
print(f'Result {a/b:5.2f}')
John
Hello John!
Result  1.33

Aligning strings by other string methods

a = "Hello"
print('|', a.center(10), '|')
print(a.rjust(14))
print(a.ljust(10))
print(a.ljust(14, '.'))
print(a.center(14, '.'))
|   Hello    |
         Hello
Hello
Hello.........
....Hello.....