f-strings
Introduction to f-strings
In Python, f-strings, also known as formatted string literals, provide an efficient and readable method of formatting and evaluating strings. They were introduced in Python 3.6 and have become a standard practice for string formatting, largely replacing the older %
formatting and str.format()
method.
The f
in f-string
stands for formatted
, it is prefixed before the string and allows for in-place expressions that can access variables in the current scope, perform arithmetic operations and call functions.
F-string Syntax and Use
Here is an example of how f-strings can be used to access variables directly within a string:
In line 6, we create an f-string by prefixing the string with the letter f
and using the curly braces {}
to embed expressions within the string that will be replaced with their values when the string is evaluated.
Beside just including variables, we can also include full expressions:
In this case, the expression a + b
within the curly braces is evaluated and its result is converted into a string and inserted into the f-string.
Note
f-strings are evaluated at runtime, which allows them to dynamically express and format data.
F-string Format Specification
F-strings can include a format specification for each variable enclosed in curly braces. This specification is introduced by a colon :
. For example, we can control the number of decimal places a floating-point number should be displayed with:
In this example :.2f
is a format specification which means: include a floating point number, format it to have 2 decimal places.
Conclusion
f-strings offer both simplicity and power to Python string formatting. They allow for fast, readable and concise string generation, enhancing overall code quality, efficiency, and scalability. Make sure to understand and use them effectively in your Python journey.