Using f-Strings for String Formatting in Python

Introduced in Python 3.6, f-Strings provide a concise and readable way to embed expressions inside string literals. They are prefixed with f or F before the opening quotation mark.

Basic Usage

name = 'Alice'
age = 30
print(f'{name} is {age} years old.')
# Output: Alice is 30 years old.

Expression Evaluation

f-Strings can evaluate expressions:

print(f'{2 + 3}')  # Output: 5

Formatting Numbers

You can format numbers within f-Strings:

pi = 3.14159
print(f'Pi rounded to two decimals: {pi:.2f}')
# Output: Pi rounded to two decimals: 3.14

Using Dictionaries

Access dictionary values:

person = {'name': 'Bob', 'age': 25}
print(f"{person['name']} is {person['age']} years old.")

Multiline f-Strings

Use triple quotes for multiline strings:

print(f"""
Name: {name}
Age: {age}
""")

Conclusion

f-Strings offer a powerful and readable way to format strings in Python. They simplify string interpolation and make your code cleaner.

Leave a Reply

Your email address will not be published. Required fields are marked *