F-strings

F-strings, also known as "formatted string literals," are a powerful and convenient way to format strings in Python. F-strings allow you to embed expressions directly inside string literals, making it easier to include variables, expressions, and even function calls within strings. F-strings are introduced in Python 3.6 and later versions.

To create an f-string, you start a string with the letter "f" or "F" and then enclose the expressions you want to include in curly braces "{}".

name = "Alice"
age = 30
greeting = f"Hello, {name}! You are {age} years old."
print(greeting)  # Output: "Hello, Alice! You are 30 years old."

In this example, the expressions "{name}" and "{age}" are evaluated and replaced with their corresponding values in the resulting string.

F-strings can include any valid Python expressions, including variables, calculations, and function calls.

radius = 5
area = f"The area of the circle with radius {radius} is {3.14 * radius ** 2}."
print(area)  # Output: "The area of the circle with radius 5 is 78.5."

You can apply various formatting options to control how the expressions are displayed within the f-string. For example:

value = 1234.56789
formatted_value = f"The value is {value:.2f}"  # Display two decimal places
print(formatted_value)  # Output: "The value is 1234.57"

In this case, ":.2f" specifies that the expression should be displayed with two decimal places.

If you want to include actual curly braces within an f-string (not expressions), you can do so by doubling them:

braces = f"{{ This is inside curly braces }}"
print(braces)  # Output: "{ This is inside curly braces }"

F-strings also support multi-line strings by using triple-quoted strings along with the "f" or "F" prefix:

name = "Alice"
age = 30
greeting = f"""
Hello, {name}!
You are {age} years old.
"""
print(greeting)

F-strings provide a more concise and readable way to format strings compared to older methods like "%" formatting and "str.format()". They make it easier to embed expressions directly within strings, leading to cleaner and more maintainable code.