Code Examples
Example 1
Using the letter f combine with {} bracket to print out the variable.
name = "John"
print(f"Hello, {name}!")
# Outputs: Hello, John!
Example 2
Multiple variables can be included in a single f-string. Each variable in curly braces is replaced with its value.
name = "John"
age = 30
print(f"My name is {name} and I am {age} years old.")
# Output: My name is John and I am 30 years old.
Example 3
Specifying decimal places. The .2f format specifier limits the output to 2 decimal places, rounding as needed.
pi = 3.14159265359
print(f"Pi to 2 decimal places: {pi:.2f}")
# Output: Pi to 2 decimal places: 3.14
Example 4
Adding commas for thousands. The , in the format specifier adds thousand separators, making large numbers more readable.
large_number = 1234567.89
print(f"Formatted with commas: {large_number:,.2f}")
# Output: Formatted with commas: 1,234,567.89
Example 5
Padding and alignment. The 8.2f reserves 8 characters total (including decimal and digits) for the number, right-aligned by default, with 2 decimal places.
cost = 42.5
print(f"Cost: ${cost:8.2f}")
# Output: Cost: $ 42.50
Example 6
Percentage formatting. The % format multiplies the number by 100 and adds a percent sign. The .1 specifies one decimal place.
rate = 0.175
print(f"Tax rate: {rate:.1%}")
# Output: Tax rate: 17.5%
Example 7
Controlling sign display. The + in the format specifier forces the display of the sign (+ or -) for both positive and negative numbers.
value = 42.5
print(f"Always show sign: {value:+.1f}")
# Output: Always show sign: +42.5
temperature = -5.75
print(f"Temperature reading: {temperature:-.2f}")
# Output: Temperature reading: -5.75