Python Formatted Strings

F-String Generator

I’ve always wanted a format string generator for Python since I can’t seem to remember all the different specifiers, so I made one. To use it, enter the variable name to format and an example value the variable will contain, then configure away!

Input:
Variable Name:
Invalid variable name
Variable Value:
Output:
Format:
f""
Formatted Value:
Format configuration:
Type:
Width:
Alignment:
Fill:
Precision:
Sign:
Grouping:

The generator is HTML, CSS, and Typescript. I referred to the format specification mini language documentation when determining the correct result to output for certain edge cases.

On Format Strings

Some interesting tidbits I learned/re-learned:

  1. When the string to center has even length and the amount of padding to insert has odd length, f-strings lean left but str.center leans right.

    >>> f"{'to':^5}"
    ' to  '
    
    >>> "to".center(5)
    '  to '
  2. The default alignment for strings (and most other types) is left, while the default alignment for numeric values is right.

    >>> f"{'pi':10}"
    'pi        '
    >>> f"{3.14:10}"
    '      3.14'
  3. The precision field, commonly used for numeric fields to limit digits after the decimal point, can also be used for strings. In this case, the field denotes the number of characters from the string to display. Used alongside the width, alignment, and fill fields, we can truncate text and insert faux-ellipses all in one f-string!

    >>> f"{'Never gonna give you up, never gonna let you down':.<18.15}"
    'Never gonna giv...'
  4. You can nest format specifiers!

    >>> cities = ["Tokyo", "Shanghai", "Mexico City", "Lima", "Paris"]
    >>> max_column_width = max(len(c) for c in cities)
    >>> for col in columns:
    ...     print(f"{col:^{max_column_width}}", end=" | ")
    ...
     Tokyo    |  Shanghai   | Mexico City |    Lima     |    Paris    |

Conclusion

It was a fun two day journey making the generator! I’ll keep updating this page as I add new features and insights. Until next time!

Additional Resources