Python·100 questions

How to format strings nicely (f-strings)?

Answer

Nice and readable string formatting is an important part of writing quality Python code. Modern versions of the language offer a powerful tool for these purposes—formatted string literals, or f-strings, which combine concise syntax and high performance.

To insert a variable's value into a string, you just need to put the letter f or F before it and enclose the variable name in curly braces. This makes the code intuitive and eliminates the need to use outdated concatenation methods or the format method.

For floating-point numbers, you can specify the number of decimal places using a format specifier, for example, specifying rounding to two decimal places right inside the curly braces.
When working with date and time objects, flexible formatting is supported using standard directives like year, month, and day.
For text alignment, you can set a fixed field width and alignment direction, which is convenient when creating text tables or reports.
Starting with Python 3.8, a useful debugging feature is available by adding an equals sign after the variable name, which automatically outputs both the name itself and its current value.

Using these features makes the data output logic clean and easily maintainable without involving third-party libraries.

Was this answer helpful?

More questions in this topic

Related questions from other topics