f-string Formatting
Python's f-strings indeed support a mini-language for formatting, allowing for a wide range of output styles. Here's a comprehensive list of the formatting options available in f-strings:
- Basic Replacement:
f"{var}"
directly replacesvar
with its value. - Expressions: Any valid Python expression can be placed inside the braces:
f"{2 * 7}"
,f"{some_func()}"
. - String Conversion
!s
: Appliesstr()
:f"{var!s}"
!r
: Appliesrepr()
:f"{var!r}"
!a
: Appliesascii()
:f"{var!a}"
- Precision for Floats and Strings
- Float Precision:
f"{var:.2f}"
rounds a floating-point number to 2 decimal places. - String Precision:
f"{var:.5}"
truncates the string to the first 5 characters.
- Float Precision:
- Float Formatting
- Fixed Point:
f"{var:.2f}"
formats a floating-point number to two decimal places. Ifvar = 3.14159
, it becomes'3.14'
. - Exponential Notation:
f"{var:.2e}"
expresses the number in scientific notation with two decimal places. For example,12345.6789
becomes'1.23e+04'
. - Percentage:
f"{var:.2%}"
converts a float to a percentage. So,0.123
becomes'12.30%'
. - Rounding:
f"{var:.0f}"
rounds the float to the nearest whole number.3.6
becomes'4'
.
- Fixed Point:
- Integer Formatting
- Binary:
f"{var:b}"
formats an integer to its binary representation.5
becomes'101'
. - Octal:
f"{var:o}"
outputs the octal format.9
becomes'11'
. - Decimal:
f"{var:d}"
is a standard decimal format.15
remains'15'
. - Hexadecimal:
f"{var:x}"
(lowercase) orf"{var:X}"
(uppercase) formats to hex.255
becomes'ff'
or'FF'
.
- Binary:
- Padding and Width
- Minimum Width:
f"{var:10}"
ensures a minimum width of 10 characters, padding with spaces if necessary. - Left-align:
f"{var:<10}"
data-preserve-html-node="true" aligns text to the left within a 10-character space. - Right-align:
f"{var:>10}"
aligns to the right, padding the left with spaces. - Center-align:
f"{var:^10}"
centers the text in a 10-character width. - Fill with Characters:
f"{var:*^10}"
centers the text and fills the padding with a specified character (in this case).
- Minimum Width:
- Number Formatting
- Thousands Separator:
f"{var:,}"
adds commas as thousands separators.1234567
becomes'1,234,567'
. - Sign:
f"{var:+}"
shows a+
orfor positive/negative numbers, while `f"{var:-}"` shows
only for negative numbers. - Leading Zeroes:
f"{var:05d}"
pads the number with leading zeroes to a total of 5 digits.
- Thousands Separator:
- Datetime Formatting
- Datetime Objects: Standard strftime formatting applies.
f"{datetime_obj:%Y-%m-%d %H:%M}"
formats a datetime object into a string like'2023-03-01 15:30'
.
- Datetime Objects: Standard strftime formatting applies.
- Nested Fields
- Nested Braces: You can nest f-strings or include dynamic width/precision.
f"{f'{var}'}"
is a simple nested example.f"{var:{width}.{precision}}"
allows for dynamic formatting.
- Nested Braces: You can nest f-strings or include dynamic width/precision.
- Literal Curly Braces
- Including Braces: To include literal
{
or}
in your string, double them:f"{{ {var} }}"
.
- Including Braces: To include literal
- Variable Name Inclusion
- Include Variable Name: Introduced in Python 3.8,
f"{var=}"
prints the variable name along with its value. Forx = 3
, it outputs'x=3'
.
- Include Variable Name: Introduced in Python 3.8,
- Alignment with Specific Width
- Specified Width Alignment:
f"{var:10}"
aligns the text to the right within a field 10 characters wide, padding with spaces.
- Specified Width Alignment:
These options offer great flexibility for formatting strings in Python, allowing for clear and concise data presentation, especially useful in applications like reporting, data analysis, and console output formatting.