DEV Community

Eric Leung
Eric Leung

Posted on • Updated on

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

The basic syntax is

{variable:width.precision}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Discussion (1)

Collapse
jimratliff profile image
jimratliff

Thanks! Very helpful. Though I wondered where you found this documented. AFAICT, the link you provided (docs.python.org/3/library/string.html#format-string-syntax) doesn't cover f-strings but only the old-school strings. After searching a little… You might consider adding links to (a) 2.4.3. Formatted string literals (docs.python.org/3/reference/lexical_analysis.html#f-strings) and/or (b) PEP 498 – Literal String Interpolation