Python Formatted Strings

Improved Python syntax for formatting strings

Formatted Strings

Python includes multiple ways of formatting a string. The traditional approach used the % operator with C-style or printf-style string formatting. Python 3 introduced the built-in format and str.format for advanced string formatting.

As of Python 3.6, formatted string literal (f-string for short) is the new and improved syntax to format strings with improved readability, flexibility, and performance. An f-string is a literal string prefixed with f. Interpolate expressions directly within a f-string using curly braces. At runtime the expressions embedded in the string are replaced with their values.

Compare the four ways of formatting a string in Python with a pi decimal and fractional value.

Loading...
Published