Skip to content

Text formatting

It is often necessary to write information on the screen, inform the user about an event. Information in the style of "Player, you currently have X lives" must be properly formatted or supplemented - after all, the value of X may change during the game, it is not possible to save such a string permanently, because each time it would be the same. Python introduces a number of ways to deal with this.

Printing strings (text)

There are four ways to print data:

  1. Without any formatting.
  2. Format printf from C language - older way.
  3. Formatting format () - newer way.
  4. Interpolation of f-string - the latest way.

All methods will be discussed below.

The print() function - supplement

We have already learned the print () function. In addition to what we already know, it offers several interesting solutions. Maybe:

  • Display several values ​​at once.
  • Define the separator between the values ​​(parameters) given to it.
  • Add string after the last value.

Specifying multiple values ​​to display at once

print() can take several values ​​as a function expecting any number of them. The arguments are separated by commas, and the function combines them and displays them as one string. By default, the arguments are separated by spaces.

    >>> print ("What", "for", "beautiful", "day", ".")
    "What a beautiful day."
    >>> print ("1", "2", 3, 4, 5)
    '1 2 3 4 5'
    >>> fruit = "orange"
    >>> print ("apple", "banana", fruit)
    'apple banana orange'

Separator

Given a few things to print the print() function, they are automatically separated by a space. If necessary, you can change the separation sign by overwriting the default value of sep. It is important that it is given last or immediately after the arguments to be printed by the function.

    >>> print ("What", "for", "beautiful", "day", ".", sep = "-")
    "What's beautiful-day-. '
    >>> print ("1", "2", 3, 4, 5, sep = "<")
    '1 <2 <3 <4 <5'
    >>> fruit = "orange"
    >>> print ("apple", "banana", fruit, sep = "+")
    'apple + banana + orange'

Final inscription

The print() function allows you to further specify which text should end in its operation. By specifying the end argument as one of the last named parameters, you can, for example, force the function to add an ellipsis, space or some text to the end of the string.

    >>> print ("What", "for", "beautiful", "day", ".", sep = "-", end = "! \ n")
    "What's beautiful-day -. \ N '
    >>> print ("1", "2", 3, 4, 5, sep = "<", end = "<... \ n")
    '1 <2 <3 <4 <5 <... \ n'
    >>> fruit = "orange"
    >>> print ("apple", "banana", fruit, sep = "+", end = "= yummy \ n")
    'apple + banana + orange = yummy \ n'

By default, the end parameter uses the "\n" newline character.

Formatting printf strings - the old way

Strings in Python have a unique built-in operation that can be accessed using the % operator. This makes it easy to perform simple positional formatting. The value given after the string or subsequent values ​​given in the data are substituted for the percent sign in the string.

    >>> name = 'Bob'
    >>> print ('Hello,% s'% name)
    'Hello, Bob'

The %s format specifier used in the example above tells Python where to substitute the value of the name represented as a string (s in %s is derived from a string).

Other specifiers can be used:

    >>> number = 42
    >>> print ('My favourite number is:% d'% number)
    'My favourite number is: 42'

    >>> error = 46372518
    >>> print ('Error number:% x'% error)
    'Error number: 2c396a6'

    >>> print ('Number:% d caused error% x'% (number, error))
    'Number: 42 caused error 2c396a6'

The specifier %d refers to numbers, while %x converts the decimal representation to hexadecimal.

In case you want to insert more than one value into the string, put them after the % sign.

Formatting strings in the style str.format() - a newer way

Formatting in a newer style gets rid of the % characters and is done by calling the function format() on the string.

    >>> name = 'Bob'
    >>> 'Hello, {}'. Format (name)
    'Hello, Bob'

You can use the format() method to perform simple positional formatting, similar to old style formatting, or refer to variable substitutions by name and use them in any order. This is quite a powerful function because it allows you to change the display order without changing the arguments passed to the format() method.

    >>> name = 'Bob'
    >>> number = 42
    >>> error = 46372518

    >>> print ('Listen, {name}, your number is {number} and the code is {code}.' format (name = name, number = number, code = error))
    "Listen, Bob, your number is 42 and the code is 46372518."

In addition to specifying arguments for the format() method, you can juggle the order by specifying it in curly brackets {}.

    title = "General"
    name = "Kenobi"
    print ("Hello there, {1} {0}". format (title, name))

Interpolation of f-string - the newest way

Python 3.6 added a new approach to formatting strings called "f strings". This new way of formatting strings lets you use embedded Python expressions inside strings. This allows you to get rid of the format() method. What's important: using this method, each string must be preceded by the letter f: f "...".

    >>> name = 'Bob'
    >>> f'Hello, {name} '
    'Hello, Bob'

The f-string formatting is able to calculate the value of an expression (e.g. a string of mathematical operations) on the run:

    a = 2
    b = 7
    print (f "{a} times {b} to the power of 2 is {(a * b) ** 2}.")

Formatting also allows us to add a specific number of spaces to the left or right of the string (this option is also available in previous ways of formatting the string):

    header1 = "Name"
    header2 = "Age"
    name = "John"
    age = 22

    print (f "| {header1: 10} | {header2: 10} |")
    print ("-" * 27)
    print (f "| {name: 10} | {age: 10} |")

Additionally, you can define how many digits after the decimal point should be displayed or display the number as a percentage:

    # Changing the way the variable is displayed
    n = 109.2345654324
    print (f "{n: .3f}") # will display 109.234

    percent = 0.71
    print (f "{percent: .1%}") # will display 71.0%