F-Strings
f-strings (short for formatted strings) are a more recent addition to Python and provide a concise and convenient way to embed expressions inside string literals, using {}
placeholders. They were introduced in Python 3.6 and are now the recommended way to format strings in Python.
Here's an example of using an f-string to print a string and a variable:
name = "Alice"
print(f"Hello, {name}!")
This will output the string "Hello, Alice!" to the console.
You can also use expressions inside f-strings:
x = 10
y = 20
print(f"{x} + {y} = {x + y}")
This will output the string "10 + 20 = 30" to the console.
f-strings also support format specifiers, similar to the %
operator. For example:
x = 3.14159
print(f"The value of pi is approximately {x:.2f}.")
This will output the string "The value of pi is approximately 3.14." to the console.
f-strings are generally easier to read and write than the %
operator, and they are also more efficient at runtime. However, they are not available in older versions of Python, so if you need to support those versions, you will need to use the % operator or another method for formatting strings.