Advanced Formatting with Python's f-strings
Today, we're diving into an advanced Python tip: f-strings!"
"F-strings, or formatted string literals, were introduced in Python 3.6. They make string formatting super easy and readable."
Basic example of using f-string:
name = "Alice"
age = 30
print(f"Hello, {name}. You are {age} years old.")
But, we can do much more with f-strings, let's have a look:
-
To format the number to desired decimal positions, e.g. :
x=7869.3278654
print(f"{x:.4f}")
Here .4f formats the number to 4 decimal places
-
Change the alignment using <,>,^ :
name="John"
print(f"{name:>30}")
It will shift the value by 30 characters left
-
Show expressions inside the f-string: "F-strings can also evaluate expressions directly inside the curly braces!"
print(“Value of 5*4 is {5*4}”)
F-strings are powerful and flexible! Try these advanced formatting tricks in your next Python project