String beautification, or how to format thongs in Python

Table of Contents

There were two methods of formatting thongs in python. This situation lasted until the emergence of Python 3.6, with the arrival of the f-strings. Today I will try to discuss all formatting methods, and give an example of their use.

The code we will work with

We will use a few simple variables that I will try to display with each of the available formatting methods.

first_name = "John"
last_name = "Doe"
born_year = 1978
current_age = 40
dict = {'text':'One', 'value': 1}

Old formatting by ‘%’ character

This formatting has been in Python for a long time. Today this method is not recommended by Python’s documentation as it has some shortcomings and may cause display problems an episode and a letter. Below is an example of using this formatting:

print("Hello %s %s. Your born year is %d. You are %d years old", first_name, last_name, born_year, current_age)

What does %s mean? It just informs the interpreter that we want to read the thong. Modifiers available:

  • %s - Character string (or any object that has a method repr such as an array))
  • **%d ** - Total figures
  • %f - floating point numbers
  • %.(X) - X-decimal number
  • %X - integer represented by the hexadecimal notation

Formatting via p.format()

This option was introduced in Python 2.6. It is an improved formatting compared to %-formatting. With str.format(), the fields we intend to replace are represented by the `{}} characters. Example:

print("Hello {2} {3}. Your born year is {1}. You are {0} years old.".format(current_age, born_year, first_name, last_name))

We can also display the contents of dictionaries by unpacking them:

print("{text} is {value}.".format(**dict))

New road, or f-Strings in Python 3.6

The introduction of f-Strings has made formatting even simpler. Example:

print(f"Hello {first_name} {last_name}. Your born year is {born_year}. You are {current_year} years old")

That’s all, f-Strings are done at start-up. You just give the ``{}` variable you define earlier. You can also use phrases, e.g. “A”:

print(f"{2 * 6}")

This code will display the value of the expression 2 * 6, or 12. You can also call functions:

name = "jane"
print(f"{name.capitalize()}")

The above code will display the text: Jane. We can also display the contents of dictionaries:

print(f"{dict['text']} is {dict['value']}.")

As you can see, it is worth using f-Strings as they increase our productivity and do not obscure the code. They are also slightly faster in execution than %-Strings and str.format().

Syntropo avatar
Syntropo
Syntropo's true identity is unknown. Maybe he is a successful blogger or writer.