String Formatting
Formatting
There are two (old one new) styles of string formatting in Python. They are very similar when dealing with simple stuff but also have a lot of in-deep presentation and text transformation options
printf-style
(%, old) - based on C printf style formatting that handles a narrower range of types and is slightly harder to use correctly, but is often faster for the cases it can handle.str.format()
(new) provides a large degree of flexibility and customization.f-strings
(Python 3.6) - inline formatting allowing to insert variables by names with format similar toformat()
🪄 Code:
📟 Output:
% (printf-style formatting)
format % values
format
is a string,%
conversion specifications in format are replaced with zero or more elements ofvalues
.
A conversion specifier contains two or more characters and has the following components, which must occur in this order:
1
. The '%' character - the start of the specifier.
2
. Mapping key (optional), key name in parentheses (for example: (somename)
).
3
. Conversion flags (optional), which affect the result of some conversion types.
4
. Minimum field width (optional). If specified as an '*
' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.
5
. Precision (optional), given as a '.
' (dot) followed by the precision. If specified as '*
' (an asterisk), the actual precision is read from the next element of the tuple in values, and the value to convert comes after the precision.
6
. Length modifier (optional).
7
. Conversion type.
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
{} / format()
It's better to use this for something that requries more complex formatting
Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.
🪄 Code:
📟 Output:
Several arguments:
🪄 Code:
📟 Output:
It is possible when using new format (format()) to specify positions:
🪄 Code:
📟 Output:
It is possible to pass arguments by names:
📟 Output:
More examples:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
Differences between formatters:
'%s %s' % ('one', 'two')
'{} {}'.format('one', 'two')
one two
'%d %d' % (1, 2)
'{} {}'.format(1, 2)
1 2
---
'{1} {0}'.format('one', 'two')
two one
'%10s' % ('test',)
'{:>10}'.format('test')
test
'%-10s' % ('test',)
'{:10}'.format('test')
test
---
'{:_<10}'.format('test')
test______
---
'{:^10}'.format('test')
test
'%.3s' % ('abcdef',)
'{:.3}'.format('abcdef')
abc
'%d' % (42,)
'{:d}'.format(42)
42
'%06.2f' % (3.141592,)
'{:06.2f}'.format(3.14159)
003.14
---
'{p.type}'.format(p=Plant())
tree
In last example assuming p is the instance of Plant class defined like:
.format() cheatsheet
123
{:10}
123
placeholder is 10
3.1415926
{:.2f}
3.14
2 decimal places
3.1415926
{:+.2f}
+3.14
2 decimal places with sign
2.71828
{:.0f}
3
No decimal places
1000000
{:,}
1,000,000
Number with comma sep
13
{:>10d}
13
Right aligned
13
{:<10d}
13
Left aligned
13
{:^10d}
13
Center aligned
.format() "cheats"
Show the same string several times
🪄 Code:
📟 Output:
Convert Values to different Bases
You can use the following letters to convert a number to their bases:
decimal, hex, octal, binary
🪄 Code:
📟 Output:
Escaping braces:
🪄 Code:
📟 Output:
f-strings formatting
New feature appeared in Python 3.6. It is possible to inject local variable right into string (variable interpolation)
Formatted string literals are prefixed with 'f' and are similar to the format strings accepted by str.format(). They contain replacement fields surrounded by curly braces. The replacement fields are expressions, which are evaluated at run time, and then formatted using the format() protocol
This feature is described by PEP 498
The format is:
🪄 Code:
📟 Output:
In case interpolating var is not defined - you'll get regular NameError:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
f-string
are evaluated only during creation (once):
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
Expressions may be evaluated directly inside a string:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
Format int value as hex:
🪄 Code:
📟 Output:
Format datetime
objects (see docs for datetime formatting:
🪄 Code:
📟 Output:
Dynamic width
🪄 Code:
📟 Output:
Templates
A bit underrated feature of builtin string module. Template is very simple template engine.
🪄 Code:
📟 Output:
Last updated
Was this helpful?