F-strings (formatted string literals) are a way to embed expressions inside string literals, using curly braces {}
. They were introduced in Python 3.6 and provide a more readable and concise way to format strings compared to older methods like str.format()
or the %
operator.
F-strings allow you to directly include variables or expressions inside strings, making string interpolation simpler and faster.
An f-string is prefixed with the letter f
or F
before the string. Expressions to be evaluated are enclosed in curly braces {}
.
Syntax:
f"string {expression} more string"
name = "Alice"
age = 25
greeting = f"Hello, {name}! You are {age} years old."
print(greeting) # Output: Hello, Alice! You are 25 years old.
F-strings can contain more than just simple variables. You can embed any valid Python expression inside the curly braces, and it will be evaluated at runtime. This includes arithmetic expressions, function calls, and other calculations.
Example:
x = 10
y = 5
result = f"The sum of {x} and {y} is {x + y}."
print(result) # Output: The sum of 10 and 5 is 15.
Example with function call:
def square(num):
return num ** 2
number = 4
message = f"The square of {number} is {square(number)}."
print(message) # Output: The square of 4 is 16.
You can control the formatting of numbers (including integers, floats, and more) using format specifiers within the f-string.
pi = 3.141592653589793
formatted = f"Pi to 2 decimal places: {pi:.2f}"
print(formatted)
# Output: Pi to 2 decimal places: 3.14
:.2f
means the number will be formatted as a floating point number with 2 digits after the decimal point.You can specify the width of the output and align the content within that width using format specifiers.
:<n>
: Left-aligned, with a minimum width of n
.:>n
: Right-aligned, with a minimum width of n
.:^n
: Center-aligned, with a minimum width of n
.:0n
: Pad with leading zeros, making the total width n
.number = 42
formatted_left = f"{number:<10}" # Left-align, width 10
formatted_right = f"{number:>10}" # Right-align, width 10
formatted_center = f"{number:^10}" # Center-align, width 10
formatted_zero_pad = f"{number:010}" # Pad with zeros, width 10
print(formatted_left) # Output: '42 '
print(formatted_right) # Output: ' 42'
print(formatted_center) # Output: ' 42 '
print(formatted_zero_pad) # Output: '0000000042'
In addition to using :.2f
for floating-point precision, you can format other numeric types similarly, specifying the width, padding, and alignment.
value = 123.456789
formatted = f"Value rounded to 3 decimal places: {value:.3f}"
print(formatted)
# Output: Value rounded to 3 decimal places: 123.457
You can format datetime
objects using strftime
style format codes inside the f-string.
from datetime import datetime
now = datetime.now()
formatted = f"Current date and time: {now:%Y-%m-%d %H:%M:%S}"
print(formatted)
# Output: Current date and time: 2024-12-26 10:30:45
Here, %Y-%m-%d %H:%M:%S
is the format code:
%Y
: 4-digit year%m
: 2-digit month%d
: 2-digit day%H
: 2-digit hour (24-hour clock)%M
: 2-digit minute%S
: 2-digit secondYou can have f-strings inside f-strings, though it is usually not very common. It can be useful in some cases.
name = "Bob"
greeting = f"Hello, {f'Nice to meet you, {name}!'}"
print(greeting)
# Output: Hello, Nice to meet you, Bob!
If you need to include literal curly braces {
or }
inside an f-string (for example, if you're generating JSON or working with regular expressions), you need to escape them by doubling them {{
or }}
.
formatted = f"{{This is a literal curly brace}}"
print(formatted)
# Output: {This is a literal curly brace}
You can use f-strings to directly format values from dictionaries by accessing the values with the key.
person = {"name": "Alice", "age": 25}
greeting = f"{person['name']} is {person['age']} years old."
print(greeting) # Output: Alice is 25 years old.
You can use f-strings for more complex expressions and function calls within the string.
Example:
x = 10
message = f"The result of {x} * 2 is {x * 2}."
print(message) # Output: The result of 10 * 2 is 20.
You can use conditional expressions (also known as ternary operators) inside f-strings.
Example (Using a conditional expression inside f-string):
is_active = True
status = f"User is {'active' if is_active else 'inactive'}."
print(status) # Output: User is active.
age = 25
formatted = f"You are {'adult' if age >= 18 else 'minor'}."
print(formatted)
# Output: You are adult.
!r
(Repr) in F-stringsIf you want to include the repr() (representation) of an object in the string, you can use !r
. This is especially useful for debugging, as it shows the "official" string representation of the object.
name = "Alice"
formatted = f"Name with repr: {name!r}"
print(formatted)
# Output: Name with repr: 'Alice'
The !r
calls the repr()
function on the variable, which for strings adds quotes around the value.
F-strings are faster than older string formatting methods like str.format()
and %
formatting because they are evaluated at runtime and do not require method calls. This makes them ideal for performance-critical applications.
f"Hello {name}"
f"Pi: {pi:.2f}"
f"{value:<10}"
, f"{value:^10}"
, f"{value:>10}"
, f"{value:010}"
f"{datetime:%Y-%m-%d %H:%M:%S}"
f"Hello, {f'Nice to meet you, {name}!'}"
f"{{this is a literal brace}}"
f"{person['name']}"
f"{'adult' if age >= 18 else 'minor'}"
!r
(repr) for Object Representation: f"{name!r}"
Objective: Practice creating f-strings with different expressions and formatting options to format and display values effectively.
Basic F-string Usage:
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"Hello, {name}! You are {age} years old.")
Formatting Numbers:
number = 3.14159
print(f"Formatted number: {number:.2f}") # Output: Formatted number: 3.14
integer = 42
print(f"Formatted integer: {integer:04d}") # Output: Formatted integer: 0042
Using Functions Inside F-strings:
def square(num):
return num ** 2
number = 5
print(f"The square of {number} is {square(number)}")
Dictionary Values with F-strings:
person = {"name": "Alice", "age": 30, "city": "New York"}
print(f"{person['name']} is {person['age']} years old and lives in {person['city']}.")
Complex Expressions:
num1 = 7
num2 = 5
sum_result = num1 + num2
print(f"The sum of {num1} and {num2} is {sum_result}. {'The sum is greater than 10.' if sum_result > 10 else 'The sum is less than or equal to 10.'}")