DEV Community

Maciej Budzyński
Maciej Budzyński

Posted on

Beautifying strings, or how to format strings in Python

There are two methods of formatting strings in python. This situation continued until Python 3.6 came along with the advent of f-strings. Today I will try to discuss all formatting methods, and give an example of their use.

This article was translated from Polish using Google Translate. The original post can be found on my blog at https://blog.budzynskimaciej.pl.

The code we will work with

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

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

Old formatting with '%' sign

This formatting has been in Python for a long time. Currently, this method is not recommended by the Python documentation as it has some drawbacks and may cause problems with the display of tuples and lists. 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)
Enter fullscreen mode Exit fullscreen mode

What does% s mean? It just tells the interpreter that we want to read a string. Available modifiers:

  • %s - A string (or any object that has a repr method, e.g. an array))
  • %d - Whole numbers
  • %f - Floating point numbers
  • %.(X) - A floating point number with a precision of X decimal numbers
  • %X - An integer represented in hexadecimal notation

Format with str.format()

This option was introduced in Python 2.6. This is an improved formatting relative to %-formatting. Thanks to str.format(), the fields we intend to substitute 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))
Enter fullscreen mode Exit fullscreen mode

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

print("{text} is {value}.".format(**dict))
Enter fullscreen mode Exit fullscreen mode

The new way, or f-Strings in Python 3.6

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

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

That's it, f-strings are executed at runtime. You just enter a variable defined earlier in {}. You can also use expressions, e.g .:

print(f"{2 * 6}")
Enter fullscreen mode Exit fullscreen mode

This code will output the value of the expression 2 * 6, which is 12. You can also call functions:

name = "jane"
print(f"{name.capitalize()}")
Enter fullscreen mode Exit fullscreen mode

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

print(f"{dict['text']} is {dict['value']}.")
Enter fullscreen mode Exit fullscreen mode

As you can see, it is worth using f-Strings, because they increase our productivity and do not obscure the code. They are also a bit faster to execute than %-Strings and str.format().

Top comments (0)