Python: f-String (Format, Template)
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
- < → Left-align
- > → Right-align
- ^ → Center-align
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
- Python: Quote String
- Python: Triple Quote String
- Python: String Escape Sequence
- Python: Unicode Escape Sequence
- Python: String Prefix Character (u f r b)
- Python: Raw String (r-prefix)
- Python: f-String (Format, Template)
- Python: Print
- Python: Join String
- Python: Format String (Convert to String)
- Python: String Operations and Methods
- Python: Search Substring
- Python: Split String
- Python: String, Check Case, Char Class
- Python: Letter Case Conversion
- Python: Unicode 🐍
- Python 2: Unicode Tutorial