F-Strings in Python

F-strings, introduced in Python 3.6, are a modern and efficient way to format strings by embedding expressions directly within string literals. This method of string interpolation and formatting is more readable and concise compared to older techniques such as % formatting and the format method. F-strings are defined by prefixing a string with the letter f or F, followed by the string content enclosed in quotes. Within the string, expressions can be placed inside curly braces {} to be evaluated and included in the final string output.

Overview

F-strings provide a powerful and efficient way to embed expressions inside string literals. They are prefixed with the letter 'f' and use curly braces {} to include Python expressions directly within the string. This feature offers a more compact and readable alternative to the traditional format method for string formatting. Their ease of use and readability have made them a popular choice among Python developers for string formatting tasks.

Components of an F-String

An f-string consists of two main components:

  1. Expression: This is the required part of an f-string. The expression is evaluated first, and the result is converted into a string. The expression can be any valid Python expression, including variables, arithmetic operations, or function calls.

  2. Format Specifier: This is an optional part that follows the expression. It allows for additional formatting of the resulting string, such as specifying the width, alignment, or number of decimal places for numerical values.

Components of an f-string Figure 2.2 Components of an f-string. The expression is the first part and is required. The expression is evaluated first, and a corresponding string is created. The second part, which is the format specifier, is optional.

Interpolating and Formatting with F-Strings

F-strings allow for seamless interpolation of variables and expressions within strings. This is achieved by placing the desired expression inside curly braces within the f-string. The expression is evaluated at runtime, and its result is inserted into the string at the specified location.

Example: Applying Format Specifiers

The following example demonstrates how to use f-strings with format specifiers to align text within a formatted output:

task_ids = [1, 2, 3]
task_names = ['Do homework', 'Laundry', 'Pay bills']
task_urgencies = [5, 3, 4]

for i in range(3):
    print(f'{task_ids[i]:^12}{task_names[i]:^12}{task_urgencies[i]:^12}') #1

# [Output the following lines:](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/177)
# [     1      Do homework      5      ](https://livebook.manning.com/book/python-how-to/chapter-2/61)
# [     2        Laundry        3      ](https://livebook.manning.com/book/python-how-to/chapter-2/61)
# [     3       Pay bills       4](https://livebook.manning.com/book/python-how-to/chapter-2/61)
#1 Applies format specifiers to the expressions

In this example, each element from the lists task_ids, task_names, and task_urgencies is formatted to be centered within a 12-character wide field. The :^12 format specifier is used to achieve this alignment, making the output neatly organized in columns.

Examples

Here are some examples demonstrating the use of f-strings:

value = 42
message = f"The answer is {value}"
print(message)

# [Output:](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/177)
# [The answer is 42](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/177)

primes = [1, 2, 3, 5]
f"sum of first 4 primes is {sum(primes)}"

# [Output:](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/177)
# [sum of first 4 primes is 11](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/177)

In the first example, the variable value is directly embedded into the string using an f-string, resulting in the output "The answer is 42". In the second example, an expression sum(primes) is evaluated and included in the string, demonstrating the ability of f-strings to handle more complex expressions.

For more detailed information, you can refer to the Python How-To and The Quick Python Book, Fourth Edition.

| Book Title | Usage of f-string | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|-------------------|-----------------|-------------------------------|---------------|-----------------------|
| [Python How-To](https://www.manning.com/books/python-how-to) | Discusses f-strings as a modern and efficient way to format strings, highlighting their readability and conciseness compared to older methods. [more](https://livebook.manning.com/book/python-how-to/chapter-2/8) | Explains components of f-strings, including expressions and optional format specifiers. [more](https://livebook.manning.com/book/python-how-to/chapter-2/54) | Connects f-strings to string interpolation and formatting, comparing with `%` formatting and `format` method. [more](https://livebook.manning.com/book/python-how-to/chapter-2/7) | Provides examples with format specifiers to align text in formatted output. [more](https://livebook.manning.com/book/python-how-to/chapter-2/61) | Demonstrates practical use in organizing data in columns using format specifiers. [more](https://livebook.manning.com/book/python-how-to/chapter-2/61) |
| [The Quick Python Book, Fourth Edition](https://www.manning.com/books/the-quick-python-book-fourth-edition) | Highlights f-strings as a powerful and efficient method for embedding expressions in strings, offering a compact alternative to the `format` method. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/177) | Focuses on the convenience and readability of f-strings for incorporating variable values and expressions. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/267) | Emphasizes the popularity of f-strings among developers for string formatting tasks. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/177) | Includes examples of embedding variables and evaluating expressions within f-strings. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/177) | Illustrates practical use in embedding variables and evaluating expressions for dynamic string creation. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/177) |

FAQ (Frequently asked questions)

Is the format specifier in an f-string mandatory?

How widely are f-strings used in Python?