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!
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:
When the string to center has even length and the amount of padding to insert has odd length, f-strings lean left but
str.centerleans right.>>> f"{'to':^5}" ' to ' >>> "to".center(5) ' to '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'The
precisionfield, 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 thewidth,alignment, andfillfields, 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...'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: ... (f"{:^{}}", end=" | ") ... | | | | |
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
- Python Format String Syntax
PyFormat.info — example-based documentation for f-strings and
.formatReal Python — a simple introduction to f-strings, also includes some pesky details