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:

1# Define some variables
2name = "Python"
3version = "3.6"
4
5# Use these variables in f-string
6welcome_message = f"Welcome to {name} version {version}"
7print(welcome_message)  # Outputs: Welcome to Python version 3.6

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:

1a = 5
2b = 10
3print(f"The sum of {a} and {b} is {a + b}")  # Outputs: The sum of 5 and 10 is 15

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:

1import math
2print(f"The value of pi to 2 decimal places is {math.pi:.2f}")  # Outputs: The value of pi to 2 decimal places is 3.14

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.