Dude Engineering

View Original

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:

  1. Basic Replacement: f"{var}" directly replaces var with its value.
  2. Expressions: Any valid Python expression can be placed inside the braces: f"{2 * 7}", f"{some_func()}".
  3. String Conversion
    • !s: Applies str(): f"{var!s}"
    • !r: Applies repr(): f"{var!r}"
    • !a: Applies ascii(): f"{var!a}"
  4. 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.
  5. Float Formatting
    • Fixed Point: f"{var:.2f}" formats a floating-point number to two decimal places. If var = 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'.
  6. 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) or f"{var:X}" (uppercase) formats to hex. 255 becomes 'ff' or 'FF'.
  7. 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).
  8. Number Formatting
    • Thousands Separator: f"{var:,}" adds commas as thousands separators. 1234567 becomes '1,234,567'.
    • Sign: f"{var:+}" shows a + or for 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.
  9. 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'.
  10. 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.
  11. Literal Curly Braces
    • Including Braces: To include literal { or } in your string, double them: f"{{ {var} }}".
  12. Variable Name Inclusion
    • Include Variable Name: Introduced in Python 3.8, f"{var=}" prints the variable name along with its value. For x = 3, it outputs 'x=3'.
  13. 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.

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.