8 months, 3 weeks

Formatting strings with f-strings





F-strings, also known as formatted string literals, are one of the most beloved Python features that came with Python 3.6. Introduced with PEP 498, they added a new way of formatting strings. 

Using % formatting: This is the oldest method and uses a substitution pattern that resembles the syntax of the printf() function from the C standard library:


>>> import math                                                                            

>>> "approximate value of π: %f" % math.pi                                
'approximate value of π: 3.141593'                                               

Using the str.format() method: This method is more convenient and less error-prone than % formatting, although it is more verbose. It enables the use of named substitution tokens as well as reusing the same value many times:

>>> import math                                                                              
>>> " approximate value of π: {:f}".format(pi=math.pi)                   
'approximate value of π: 3.141593'                                                 

Using formatted string literals (so called f-strings). This is the most concise, flexible, and convenient option for formatting strings. It automatically substitutes values in literals using variables and expressions from local 
namespaces

>>> import math                                                                           
>>> f"approximate value of π: {math.pi:f}"                                  
'approximate value of π: 3.141593'                                              


Responses(0)







Related