Python f string format float | Example code

In Python programming formatted string literals, 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 specifies then the additional space is used.
  • precision indicates the number of characters used after the decimal point

Python f string format float exampel

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 and suggestions on this Python string format.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.