In Python versions 3.6 and above, literal string interpolation receives the hype; however, did you know that there are several ways to format strings in Python?
String Formatting (printf-style)
String objects have a built-in operation: the % operator (modulo).
If the operator is used once in a string, then a single non-tuple object may be used:
|
|
In this example, the conversion type, %s
(string), will be replaced by “onions”.
Otherwise, the strings must be placed within a tuple of exact length or a dictionary.
Tuple:
|
|
Dictionary:
|
|
Additionally, there are flag characters and other types. To represent an integer, the type %d
(for decimal) could be used. In the example below, %d
was used in combination with the 0
flag character to add trailing zeros.
|
|
More information can be found here about the printf-style string formatting.
String Format Method
While the predecessor leveraged type conversions and flag characters, Python 3 introduced the str.format(*args, **kwargs)
string method.
Using positional arguments:
|
|
Using indices:
|
|
Using repeated indices:
|
|
Named arguments:
|
|
Accessing arguments’ items:
|
|
Thousands separator:
|
|
… and more format string syntax tricks here.
Literal String Interpolation
Python 3.6 introduced literal string interpolation, also known as f-strings. F-strings allow you to embed expressions inside string constants.
|
|
F-strings are prefixed with the letter f
and allow you to complete operations inline within the string.
|
|
The existing syntax from the str.format()
method can be used.
|
|