Efficient String Formatting With Python f-Strings
f-string simplifies string formatting, which provides a concise and readable way to embed expressions inside string literals.
Join the DZone community and get the full member experience.
Join For Freef-strings are a feature introduced in Python 3.6 to simplify string formatting. It provides a concise and readable way to embed expressions inside string literals, making string formatting more intuitive and efficient.
Basic Syntax
f-strings are created by prefixing a string literal with the letter 'f.' Inside the string, expressions enclosed in curly braces {} are evaluated and replaced with their values at runtime.
name = "John Doe"
age = 35
message = f"Hello, my name is {name} and I am {age} years old."
print(message)
Expression Inside f-strings
f-strings supports the inclusion of dynamic values by placing the expression within curly braces {} as mentioned earlier. These expressions are evaluated at runtime, allowing for the inclusion of variables, calculations, functions, ternary operations, and other dynamic content.
x = 10
y = 20
result = f"The sum of {x} and {y} is {x + y}"
print(result) # 30
Variable Access
Variables in the current scope can be accessed directly within the f-string. This provides a concise way to reference and display variable values.
name = "John Doe"
age = 35
message = f"Hello, my name is {name} and I am {age} years old."
print(message) # Hello, my name is John Doe and I am 35 years old.
Function Calls
We can call functions and methods inside f-strings, and their return values will be included in the resulting string.
name = "John Doe"
age = 35
def greet(name):
return f"Hello {name} here"
message = f"{greet(name)} and I am {age} years old."
print(message) # Hello John Doe here and I am 35 years old.
Another example would be to use an existing function inside f-string, for example, finding the max number from a list of numbers.
numbers = [1,2,3,4,5]
result = f"The largest number is {max(numbers)}."
print(result) # Output: The largest number is 5.
Formatting Options
f-strings support various formatting options, similar to the format () method. You can specify the format using the ":" character inside the curly braces.
pi = 3.141592653589793
formatted_pi = f"Value of pi: {pi:.2f}"
print(formatted_pi) # 3.14
In the example above, .2f specifies that the floating-point number should be formatted with two decimal places.
Conditional Expressions (Ternary Operator)
We can use the ternary operator inside the f-strings for evaluating conditional expressions.
def result(score):
return f"The student {'passed' if score >=70 else 'failed'}"
result(85) # 'The student passed'
result(60) # 'The student failed'
Additional Key Points
- List Comprehensions: We can use list comprehensions inside f-strings to create or display lists.
numbers = [1,2,3,4,5]
result = f"The Squares of numbers inside the list are {[n * 2 for n in numbers]}"
# 'The Squares of numbers inside the list are [2, 4, 6, 8, 10]'
- Attribute Access: Attributes of objects can be accessed directly with-in f-strings.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("John Doe", 35)
description = f"{person.name} is {person.age} years old."
- Dictionary Access: f-strings allow accessing values from the dictionary using keys.
student_grades = {"John": 90, "Bob": 80, "Charlie": 95}
message = f"John scored {student_grades['John']} in the exam."
- Date and Time Formatting: When working with date and time objects, expressions inside f-strings can format and display them.
from datetime import datetime
now = datetime.now()
formatted_date = f"Current date and time: {now:%Y-%m-%d %H:%M:%S}."
- Multiline Strings: f-strings allow us to create multi-line strings easily by enclosing expressions in triple quotes (
'''
or"""
). Here's an example of using a multi-line f-string:
name = "John Doe"
age = 35
occupation = "Software Engineer"
# Multi-line f-string
message = f"""
Hello, my name is {name}.
I am {age} years old.
I work as a {occupation}.
"""
print(message)
Advantages of Using f-strings Over Other String Formatting Options in Python
- Performance: Benchmarks often show f-strings to be slightly faster than other formatting methods.
import timeit
import timeit
def fstring_formatting():
name = "John"
age = 35
message = f"Hello, {name}! You are {age} years old."
def format_method():
name = "John"
age = 35
message = "Hello, {}! You are {} years old.".format(name, age)
def percent_operator():
name = "John"
age = 35
message = "Hello, %s! You are %d years old." % (name, age)
fstring_time = timeit.timeit(fstring_formatting, number=9000000)
format_time = timeit.timeit(format_method, number=9000000)
percent_time = timeit.timeit(percent_operator, number=9000000)
print("F-string time:", fstring_time) # 1.5446170830000483
print("Format method time:", format_time) # 2.038085499999852
print("Percent operator time:", percent_time) # 2.0135472500001015
- Readability: f-strings allow variables, expressions, and function calls to be directly embedded within the string, making for cleaner and more intuitive code. It also eliminates the need for multiple string concatenations and improves readability.
- Clearer formatting: The intent of the string formatting is more evident within the string itself, making code easier to understand and maintain.
Opinions expressed by DZone contributors are their own.
Comments