Formatted Strings in Python: Syntax, Usage, and Examples
How to Use Formatted Strings in Python
age = 42
greeting = f"Hello, {name}. You are {age} years old."
When to Use Formatted Strings
In Python, string formatting with f-strings is useful in various scenarios. Examples include data output formatting, logging, and dynamic content generation. Python f-strings are particularly useful for including variables or expressions within strings.
Examples of Formatted Strings in Python
Dynamic Content Creation
action = "uploaded a video"
message = f"Thank you, {username}. You have successfully {action}."
Complex Calculations Display
interest_rate = 0.05
years = 5
final_amount = principal_amount * (1 + interest_rate) ** years
print(f"After {years} years, your investment will be worth ${final_amount:.2f}.")
Iterating Over Data
for i, product in enumerate(products, start=1): print(f"Product {i}: {product}")
Conditional Outputs in Messages
free_shipping_threshold = 100
shipping_status = "eligible" if order_total >= free_shipping_threshold else "not eligible"
print(f"Your order is {shipping_status} for free shipping.")
Formatting Date and Time for User Interfaces
user_last_login = datetime(2024, 2, 16, 11, 38)
print(f"Last login: {user_last_login:%B %d, %Y at %H:%M}")
Learn More About String Formatting in Python
F-strings can include more than variables and values. They can include expressions, function calls, and even conditional logic:
return x * 2
value = 10
print(f"Double {value} is {double(value)}")
Python's so-called format mini-language provides advanced control over string formatting. Instead of just inserting values, the format mini-language allows you to specify field width, alignment, precision, and more. However, the formatting syntax must follow a specific order, with each modifier category having specific symbols.
The format mini-language supports a wide range of options for creating string representations of values. Numbers and dates are the most common values to format:
- You can control the precision of floating-point numbers, display format, or the grouping of thousands with number formatting:
print(f"Formatted Number: {number:,.2f}") # Includes thousands separator
You can also customize the formatting of dates and times:
current_date = datetime.now()
print(f"Current date: {current_date:%Y-%m-%d}")
Refer to the official Python documentation if you want to learn about additional capabilities of the format mini-language.
Python f-string formatting only became popular with Python 3.6. Before f-strings, formatting strings required the % operator, the str.format() method, or template strings.
The % operator is Python's original method for string formatting, inspired by the printf syntax of the C programming language. The % operator method uses format specifiers like %s for strings and %d for integers to insert values into a string template.
age = 42
print("My name is %s and I am %d years old." % (name, age))
Introduced in Python 2.6, the str.format() method is more flexible than the % operator. The string module's formatting function supports both positional and keyword arguments, with placeholders surrounded by curly braces ( { and } ).
age = 42
print("My name is {0} and I am {1} years old.".format(name, age))
Python's string Template class provides another way to format strings using a simpler syntax. While less powerful, it can be useful for straightforward substitutions. An example might be handling user-generated format strings (to avoid security issues).
template = Template("My name is $name and I am $age years old.")
print(template.substitute(name=name, age=age))
F-strings became the most popular string formatting method in Python because of their speed and straightforward syntax. However, knowing the other string formatting methods is still important when working with older Python code.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.