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 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
Description | Code | Output |
---|
Basic integer formatting | f"The value is {value}" | The value is 42 |
Left-aligned, width 5 | f"The value is {value:<5}" | The value is 42 |
Right-aligned, width 5 | f"The value is {value:>5}" | The value is 42 |
Center-aligned, width 5 | f"The value is {value:^5}" | The value is 42 |
Zero-padded, width 5 | f"The value is {value:05}" | The value is 00042 |
Thousand separator | f"The value is {value:,}" | The value is 1,234,567 |
Hexadecimal | f"The value in hexadecimal is {value:x}" | The value in hexadecimal is ff |
Octal | f"The value in octal is {value:o}" | The value in octal is 377 |
Binary | f"The value in binary is {value:b}" | The value in binary is 11111111 |
Right-aligned, width 10, ‘*’ fill | f"The value is {value:*>10}" | The value is *******42 |
Center-aligned, width 10 | f"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.