Created
February 26, 2024 14:57
-
-
Save leandjb/c2b7c54f8da08af2d25252a6b28e3495 to your computer and use it in GitHub Desktop.
Tips for using Python F-strings more effectively and complete with small code examples.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#1. Expressions Inside Braces | |
name = "Alice" | |
age = 30 | |
print(f"{name} is {age + 1} years old next year.") | |
#2. Calling Functions | |
def greet(name): | |
return f"Hello, {name}!" | |
print(f"{greet('Bob')}") | |
#3. Format Specifiers | |
price = 49.99 | |
print(f"The price is {price:.2f} dollars.") | |
#4. Dictionary Values | |
person = {'name': 'Alice', 'age': 30} | |
print(f"{person['name']} is {person['age']} years old.") | |
#5. Date Formatting | |
from datetime import datetime | |
now = datetime.now() | |
print(f"The current time is {now:%Y-%m-%d %H:%M}.") | |
#6. Multiline F-strings | |
name = "Alice" | |
profession = "developer" | |
bio = (f"Name: {name}\n" | |
f"Profession: {profession}") | |
print(bio) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment