Python f-string Formatting: A Practical Guide
Python f-string Formatting: A Practical Guide ๐ก
Since Python 3.6, f-strings have become the standard way to format strings. They are faster, cleaner, and easier to read. Let’s look at some practical examples.
✅ Inserting variables
Just wrap variables inside curly braces {} prefixed with an f before the string.
name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old."
print(message)
✅ Numeric formatting
You can control precision, padding, alignment, and more using format specifiers.
score = 93.4567
print(f"Rounded score: {score:.2f}") # Rounded score: 93.46
✅ Using expressions and dictionary keys
You can even use expressions and access dictionary elements inside the f-string.
user = {"name": "Bob", "level": "admin"}
print(f"User {user['name']} has {user['level']} access.")
f-strings are not only concise but also more readable and efficient than other formatting methods like % or .format(). Use them by default when working with strings!
Readable code is powerful code. Keep writing better code every day with CodeVerse. ๐
Icons by Flaticon
Comments
Post a Comment