Logo

dev-resources.site

for different kinds of informations.

Print fixed fields using f-strings in Python

Published at
8/18/2020
Categories
python
strings
formatting
Author
Eric Leung
Categories
3 categories in total
python
open
strings
open
formatting
open
Print fixed fields using f-strings in Python

Formatting strings in Python is very common. Older styles use a combination of % and .format() to format strings. Newer styles use what are called f-strings.

Formatting strings using f-strings are very flexible. One thing that wasn't clear is how to specify the width of strings.

To create an f-string, you must be using Python 3 and type out something like this.

greet = 'Hello'
print(f"{greet}, World!")
# Hello, World

I ran into a situation where I wanted to format an aligned text. To do so, you can use the syntax used in other Python formatting.

init = 34
end = 253
print(f"You had this much money      : ${init:5}")
print(f"Now you have this much money : ${end:5}")
# You had this much money      : $   34
# Now you have this much money : $  253
#                Spacing width    12345

Note the annotation of spacing width with the numbers 1 through 5 to show the spacing differences.

The basic syntax is

{variable:width.precision}

With this syntax, you can even pass variables for each of those values for more dynamic control.

width = 10
precision = 4
value = decimal.Decimal("12.34567")
f"result: {value:{width}.{precision}}"
# result:      12.35

One last fun thing you have control over is you can align these values using the less than and greater than symbols for right-aligned (>) or left-aligned (<).

place = 'here'
print(f"You can have the word {place:<10}")
print(f"Or you have the word  {place:>10}")
# You can have the word here      
# Or you have the word        here

More reference material on how to format strings can be found here.

Featured ones: