Skip to content

Python f-string format integer

  • by

Python f-string format also allows you to display an integer in different bases. The f-strings have the f prefix and use {} brackets to evaluate values.

Python f-string format integer

Simple example code.

age = 100

print('%d years old' % (age))
print('{} years old'.format(age))
print(f'{age} years old')

Output:

Python f-string format integer

Python f-string integer with thousands of commas and space padded, the number is the width of the field. By default, they are right aligned.

a = 123456789
b = 12345678

print(f"{a:12,d}\n{b:12,d}")

Output:

 123,456,789   
  12,345,678

Floating point values have the f suffix. We can also specify the precision: the number of decimal places. The precision is a value that goes right after the dot character.

val = 10.3

print(f'{val:.2f}')
print(f'{val:.5f}')

Output:

10.30
10.30000
DescriptionCodeOutput
Basic integer formattingf"The value is {value}"The value is 42
Left-aligned, width 5f"The value is {value:<5}"The value is 42
Right-aligned, width 5f"The value is {value:>5}"The value is 42
Center-aligned, width 5f"The value is {value:^5}"The value is 42
Zero-padded, width 5f"The value is {value:05}"The value is 00042
Thousand separatorf"The value is {value:,}"The value is 1,234,567
Hexadecimalf"The value in hexadecimal is {value:x}"The value in hexadecimal is ff
Octalf"The value in octal is {value:o}"The value in octal is 377
Binaryf"The value in binary is {value:b}"The value in binary is 11111111
Right-aligned, width 10, ‘*’ fillf"The value is {value:*>10}"The value is *******42
Center-aligned, width 10f"The value is {value:^10}"The value is 42

Comment if you have any doubts or suggestions on this Python format string.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading