Skip to content

Python f string format float | Example code

  • by

In Python programming, formatted string literals, are simply called “f-strings“. They are called f-strings because you need to prefix a string with the letter ‘F in order to get an f-string. The letter ‘f’ also indicates that these strings are used for formatting

f'{value:{width}.{precision}}'

Include the type specifier in your format expression:

>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'

where:

  • value is any expression that evaluates to a number
  • width specifies the number of characters used in total to display, but if value needs more space than the width specified then the additional space is used.
  • precision indicates the number of characters used after the decimal point

Python f string format float example

The following is a basic example of the use of f-strings:

x = 4.5
print(f'The variable x: {x}')

Output:

Python f string format float

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

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