Advanced f-String Techniques and Examples
Beyond the basic usage of f-Strings, there are several advanced techniques and features that can help you create more powerful and flexible string formatting.
You can use various formatting specifiers within the curly braces to control the appearance of the output. For example, you can control the number of decimal places, align the text, or add thousands separators.
price = 9.99
print(f"The price is ${price:.2f}") ## Output: The price is $9.99
print(f"The price is ${price:>10.2f}") ## Output: The price is $9.99
print(f"The price is ${price:,}") ## Output: The price is 9.99
You can use conditional expressions within f-Strings to dynamically format the output based on certain conditions.
age = 25
print(f"You are {'adult' if age >= 18 else 'minor'}") ## Output: You are adult
Calling Functions
You can call functions within f-Strings to perform more complex transformations on the data.
def format_name(first, last):
return f"{last.upper()}, {first.capitalize()}"
name = format_name("john", "doe")
print(f"The person's name is {name}") ## Output: The person's name is DOE, John
Multiline f-Strings
f-Strings can also be used to create multiline strings, which can be useful for formatting complex output.
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
info = f"""
Name: {person['name']}
Age: {person['age']}
City: {person['city']}
"""
print(info)
This will output:
Name: Alice
Age: 30
City: New York
By exploring these advanced f-String techniques, you can create more sophisticated and dynamic string formatting in your Python code.