A formatted string literal, also known as an f-string, is a way to embed expressions inside string literals, using curly braces {}. The expressions are evaluated at runtime and their values are inserted into the string. Here's an example:
name = "Alice"age = 25print(f"My name is {name} and I am {age} years old.") |
In this example, the f-string is enclosed in the quotes " and begins with the f character, which signals that it is a formatted string literal. Inside the curly braces {}, expressions are evaluated and their values are inserted into the string. The expressions can be simple variables, function calls, or any valid Python expression.
Formatted string literals were introduced in Python 3.6 and are a convenient way to format strings without using the format() method or format specifiers. They can be more concise and easier to read than other string formatting methods, especially for simple cases.
Formatted string literals can also include format specifiers, using the same syntax as in the format() method. For example:
price = 19.99print(f"The price is ${price:.2f}") |
In this example, the format specifier :.2f is used to format the price variable as a floating-point number with two decimal places. The resulting string will be "The price is $19.99".
You can find more information on formatted string literals in the Python documentation.