23. Python String Formatting
Python String Formatting
To make sure a string displays exactly as expected, we format it. String formatting allows you to inject variables into strings, control decimal precision, align text, and pad numbers with zeros.
While Python has older methods like the % operator and .format(), the modern, standard, and most readable way to format strings in Python 3.6+ is using f-Strings (Formatted String Literals).
F-Strings Refresher
To specify a string as an f-string, simply put an f (or F) immediately in front of the opening quotation mark. Then, you can place variables directly inside curly braces {}.
Evaluating Expressions
F-strings do more than just insert variables; they can evaluate full Python expressions (math, functions, methods) directly inside the curly braces.
Formatting Numbers (Decimals)
When working with floats (especially currency), you often want to restrict the number of decimal places. You can add a format specifier by adding a colon : inside the curly braces, followed by the format code.
Formatting Large Numbers (Commas)
Large numbers are difficult to read without separators. You can use the comma , format specifier to automatically insert thousand separators.
Formatting Percentages
If you have a decimal ratio that you want to display as a percentage, use the % format specifier. It multiplies the number by 100 and adds a percent sign automatically.
Padding and Alignment
When printing data in tables or columns, you need text to line up perfectly. You can specify a minimum width and an alignment direction.
- :< Left aligns the result (within the available space)
- :> Right aligns the result
- :^ Center aligns the result
Padding with Zeros
Sometimes IDs, invoice numbers, or binary strings need to be padded with leading zeros to maintain a consistent length. Use the 0 flag before the width number.
Knowledge Check
Ready to test your understanding of 23. Python String Formatting?