String Formatting Cookbook
I started this string formatting cookbook as a quick reference to help me format numbers and strings. It has grown over time and expanded into a full book, 📕 Working with Python a free downloadable PDF with even more sections, examples and content.
Python 3.6 introduced formatted string literals, referred to as f-strings, as another method to help format strings. F-strings are a powerful and flexible way to format strings in Python. An f-string is a string prefixed with f
or F
. They allow you to embed expressions inside string literals, using curly braces {}
. The expressions are evaluated at runtime and then formatted according to the format specification inside the braces.
F-strings are now the defacto standard way to format strings since they are far simpler to use and read. Using f-strings in Python is similar to JavaScript’s template literals, if you are familiar with them.
Here’s an example comparing the three ways to format a float number:
pi = 3.14159
print(f" pi: {pi:.2f}") # f-string
print(" pi: {:.2f}".format( pi )) # .format()
print(" pi: %1.2f " % pi) # older Python 2
Number formatting
This table shows various ways to format numbers using Python’s formatted string literals and str.format()
, including examples for both float formatting and integer formatting.
To run examples use: print(f"{NUM:FORMAT}")
Number | Format | Output | Description |
---|---|---|---|
3.1415926 | {:.2f} | 3.14 | Format float 2 decimal places |
3.1415926 | {:+.2f} | +3.14 | Format float 2 decimal places with sign |
-1 | {:+.2f} | -1.00 | Format float 2 decimal places with sign |
2.71828 | {:.0f} | 3 | Format float with no decimal places |
5 | {:0>2d} | 05 | Pad number with zeros (left padding, width 2) |
5 | {:x<4d} | 5xxx | Pad number with x’s (right padding, width 4) |
1000000 | {:,} | 1,000,000 | Number format with comma separator |
0.25 | {:.2%} | 25.00% | Format percentage |
1000000000 | {:.2e} | 1.00e+09 | Exponent notation |
13 | {:10d} | 13 | Right aligned (default, width 10) |
13 | {:<10d} | 13 | Left aligned (width 10) |
13 | {:^10d} | 13 | Center aligned (width 10) |
Formatted string literals
Here are a couple of examples of basic string substitution using f-strings the {}
is the placeholder for substituted variables. If no format is specified, it will insert and format as a string.
Basic Substituion
adj = "tasty"
noun = "burger"
s = f"hmmm, this is a {adj} {noun}"
Do math with f-strings:
print( f"Do math: 3 * 6 = {3 * 6}" )
>>> Do math: 3 * 6 = 18
Call functions with f-strings;
verb = "runs"
print( f"The girl {verb.upper()} quickly." )
>>> The girl RUNS quickly.
Delimiting f-strings
Use f-strings with the three different type of quotation marks in Python, single, double, or triple quotes. The following will all output the same:
name = "Fred"
print( f'{name}' )
print( f"{name}" )
print( f"""{name}""" )
You can also use an uppercase F
to prefix a string, but it is uncommon usage, so best to stick with just f
string prefix.
Escaping braces
If you need to use braces when using f-strings just double them up:
print(f" The empty set is often represented as {% raw %}{{0}}{% endraw %}")
~~ The empty set is often represented as {0}
Nested f-strings
Use {}
as a variable inside the formatting to use a variable as part of the formating. This example uses a precision variable to control how many decimal places to show:
pi = 3.1415926
precision = 4
print(f"{pi:.{precision}f}")
>>> 3.1416
Convert values to different bases
A surprising use with the string format command is to convert numbers to different bases. Use the letter in the formatter to indicate the number base: decimal, hex, octal, or binary.
This example formats the number 21
in each base:
num = 21
"f{num:d} - {num:x} - {num:o} - {num:b} "
>>> 21 - 15 - 25 - 10101
F-String error
The one thing to be careful with is mixing the two formats, if {}
are used inside of an f-string, it will give the error:
SyntaxError: f-string: empty expression not allowed
Each set of brackets used in an f-string requires a value or variable.
Formatting tips with .format()
The format()
function offers some capabilities where it can the formatting tool to use. Here are a couple of examples of tips and tricks to format strings in Python:
Substitution positioning
A benefit of .format()
not available in f-strings is using the numeric position of the variables and changing them in the strings, this gives flexibility, if you make a mistake in the order you can easily correct without shuffling all the variables around.
s1 = " {0} is better than {1} ".format("emacs", "vim")
s2 = " {1} is better than {0} ".format("emacs", "vim")
Reuse same variable multiple times
Using % to format requires a strict ordering of variables, the .format()
method allows you to put them in any order as well as repeating for reuse.
"Oh {0}, {0}! wherefore art thou {0}?".format("Romeo")
>>> 'Oh Romeo, Romeo! wherefore art thou Romeo?'
Use format as a function
Use .format
as a function to separate text and formatting from code. For example, at the beginning of a program include all the formats for later use.
## defining formats
email_f = "Your email address was {email}".format
## use elsewhere
print(email_f(email="bob@example.com"))
Using format as a function can be used to adjust formating by user preference.
## set user preferred format
num_format = "{:,}".format
## use elsewhere
print(num_format(1000000))
Internationalization
To use locale specific formatting for numbers, first set the locale, and then use the formating code n
instead of d
. For example, using commas or periods to separate thousands in numbers based on the user’s locale.
Here is an example, setting locale and formatting a number to display the proper separator:
import locale
locale.setlocale(locale.LC_ALL, '')
print("{:n}".format(1000000))
Table formatting data
Use the width and the left and right justification to align your data into a nice table format. Here’s an example using the .format
method with rows of data:
# data
starters = [
[ 'Andre Iguodala', 4, 3, 7 ],
[ 'Klay Thompson', 5, 0, 21 ],
[ 'Stephen Curry', 5, 8, 36 ],
[ 'Draymon Green', 9, 4, 11 ],
[ 'Andrew Bogut', 3, 0, 2 ],
]
# define format row
row = "| {player:<16s} | {reb:2d} | {ast:2d} | {pts:2d} |".format
for p in starters:
print(row(player=p[0], reb=p[1], ast=p[2], pts=p[3]))
This would output:
| Andre Iguodala | 4 | 3 | 7 |
| Klay Thompson | 5 | 0 | 21 |
| Stephen Curry | 5 | 8 | 36 |
| Draymon Green | 9 | 4 | 11 |
| Andrew Bogut | 3 | 0 | 2 |
Older % string formatter
An example comparing variable substitution with the older %
method vs. .format()
:
s1 = "cats"
s2 = "dogs"
s3 = " %s and %s living together" % (s1, s2)
s4 = " {} and {} living together ".format(s1, s2)
Using the older format method, I would often get the errors:
TypeError: not enough arguments for format string
or
TypeError: not all arguments converted during string formatting
because I miscounted my substitution variables, doing something like the following made it easy to miss a variable.
Using one of the new Python string formatters you can use numbered parameters so you don’t have to count how many you have, at least on half of it.
set = " ({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}) ".format(a,b,c,d,e,f,g)
Or better yet using f-strings, even simpler:
set = f" ({a}, {b}, {c}, {d}, {e}, {f}, {g} ) "
Resources
- Python String Library – Standard Library Documentation
- Working with Python book - free downloadable PDF