Python: f-String (Format, Template)

By Xah Lee. Date: . Last updated: .

What is F String

f in front of the string quote means the string can embed variable and expressions, via the syntax {}.

new in python 3.6 (year 2016)

# f-string
x = 3
y = f"i have {x} cats"
print(y)
# "i have 3 cats"

Format Floats

inside the curly brackets {}, you can specify how the value is formatted. The format specification code syntax is similar to

# print float, 2 decimal places
print(f"{123.45678:.2f}")
# 123.46

# print float, 4 decimal places
print(f"{123.45678:.4f}")
# 123.4568

Format Percentage

# format percentage

# print as percentage, with 1 decimal place
print(f"{0.123456:.1%}")
# 12.3%

# print as percentage, with 2 decimal places
print(f"{0.123456:.2%}")
# 12.35%

Add Comma as Digits Group Separator

print(f"{1234567890:,}")
# 1,234,567,890

Padding and Alignment

xname = "Alice"
xx = f"""
Left:   |{xname:<10}|
Right:  |{xname:>10}|
Center: |{xname:^10}|"""
print(xx)

# Left:   |Alice     |
# Right:  |     Alice|
# Center: |  Alice   |

Python, format string

Python, String