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

Do 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

Your email address will not be published. Required fields are marked *