Skip to main content

f strings in Python

Learning Sections          show


f-strings in Python

f-strings, introduced in Python 3.6, provide a way to embed expressions inside string literals, using curly braces {}. They are prefixed with the letter f or F.


Basic Usage

f-strings are a concise and readable way to format strings.

# Basic usage of f-strings
name = "Alice"
age = 30
greeting = f"Hello, my name is {name} and I am {age} years old."
print(greeting)  # Output: Hello, my name is Alice and I am 30 years old.

Expressions in f-strings

f-strings can include expressions, which are evaluated at runtime.

# Expressions inside f-strings
a = 5
b = 10
result = f"{a+b}"
print(result)  # Output: 15

Calling Functions

You can call functions within f-strings.

# Calling functions inside f-strings
def greet(name):
    return f"Hello, {name}!"

print(greet("World"))  # Output: Hello, World!

Using Format Specifiers

f-strings support format specifiers for controlling the appearance of values.

# Using format specifiers with f-strings
value = 123.456
formatted_value = f"{value:.2f}"
print(formatted_value)  # Output: 123.46

Multi-line f-strings

f-strings can span multiple lines using triple quotes.

# Multi-line f-strings
name = "Alice"
age = 30
greeting = f"""Hello, my name is {name}
and I am {age} years old."""
print(greeting)  # Output: Hello, my name is Alice
                                    #          and I am 30 years old.

Escaping Braces

To include literal curly braces in the output, double them {{ and }}.

# Escaping braces in f-strings
text = f"{{This is a literal brace}}"
print(text)  # Output: {This is a literal brace}