- String Formatting
- Number formatting
- String .format() basics
- Substitution positioning
- Variable formatting
- Older % string formatter
- Formatted string literals
- Do math with f-strings:
- Call functions with f-strings;
- Delimiting f-strings
- F-String error
- Formatting tips with .format()
- Reuse same variable multiple times
- Convert values to different bases
- Use format as a function
- Internationalization
- Escaping braces
- Table formatting data
- Resources
- Formatting Numbers for Printing in Python
- Format numbers rounded to certain decimal places
- Display separator character between thousands
- Format floating point numbers as percentages
- Wrapping Up
- Phil Best
String Formatting
Python v2.7 introduced a new string formatting method, that is now the default in Python3. I started this string formatting cookbook as a quick reference to help me format numbers and strings. Thanks to other contributors I’ve expanded the examples over time.
Python 3.6 introduced, formatted string literals, often referred to as f-strings as another method to help format strings. It is simpler to prepend an f to the string then append .format() . 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(" pi = %1.2f " % pi) # older print(" pi = ".format( pi )) # .format() print(f" pi = pi:.2f>") # f-string
Number formatting
This table shows various ways to format numbers using Python’s str.format() and formatted string literals, including examples for both float formatting and integer formatting.
To run examples use: print(f»») or print(«».format(NUM));
Number | Format | Output | Description |
---|---|---|---|
3.1415926 | 3.14 | Format float 2 decimal places | |
3.1415926 | +3.14 | Format float 2 decimal places with sign | |
-1 | -1.00 | Format float 2 decimal places with sign | |
2.71828 | 3 | Format float with no decimal places | |
5 | 2d> | 05 | Pad number with zeros (left padding, width 2) |
5 | 5xxx | Pad number with x’s (right padding, width 4) | |
1000000 | 1,000,000 | Number format with comma separator | |
0.25 | 25.00% | Format percentage | |
1000000000 | 1.00e+09 | Exponent notation | |
13 | 13 | Right aligned (default, width 10) | |
13 | 13 | Left aligned (width 10) | |
13 | 13 | Center aligned (width 10) |
String .format() basics
Here are a couple of examples of basic string substitution, the <> is the placeholder for substituted variables. If no format is specified, it will insert and format as a string.
s1 = "show me the <>".format("money") s2 = "hmmm, this is a <> <>".format("tasty", "burger")
With formatted string literals, this is simply:
s1 = f"show me the money>" s2 = f"hmmm, this is a tasty> burger>"
Substitution positioning
One benefit of .format() that is not available in f-strings is using the numeric position of the variables and change them in the strings, this gives some flexibility when doing the formatting, if you make a mistake in the order you can easily correct without shuffling all the variables around.
s1 = " is better than ".format("emacs", "vim") s2 = " is better than ".format("emacs", "vim")
Variable formatting
You can use <> as a variable inside the formatting brackets (h/t Peter Beens for tip). This example uses a precision variable to control how many decimal places to show:
pi = 3.1415926 precision = 4 print( "<>f>".format( pi, precision ) ) >>> 3.1415
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
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 = " ( , , , , , , , ) ".format(a,b,c,d,e,f,g)
Formatted string literals
As shown above, formatted string literals, or f-strings, use a shorter syntax making it easier and more template-like. F-strings also support functions inside of the brackets < >this allows you to:
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
You can use f-strings using 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>""" )
F-String error
The one thing you’ll want to be careful is mixing the two formats, if you try to use <> inside of an f-string, you will get 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 additional features and capabilities, here are a few useful tips and tricks to format strings in Python:
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 , ! wherefore art thou ?".format("Romeo") >>> 'Oh Romeo, Romeo! wherefore art thou Romeo?'
Convert values to different bases
A surprising use, you can use the string format command 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:
" - - - ".format(21) >>> 21 - 15 - 25 - 10101
Use format as a function
You can use .format as a function to separate text and formatting from code. For example, at the beginning of your program include all your formats for later use.
## defining formats email_f = "Your email address was ".format ## use elsewhere print(email_f(email="bob@example.com"))
Hat tip to earthboundkids who provided this on reddit.
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, you need to 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(" ".format(1000000))
Escaping braces
If you need to use braces when using str.format() just double them up:
print(" The <> set is often represented as % raw %>>% endraw %>".format("empty")) ~~ The empty set is often represented as 0>
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 to show how to format:
# 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 = "| | | | |".format for p in starters: print(row(player=p[0], reb=p[1], ast=p[2], pts=p[3]))
| 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 |
Resources
- Python String Library – Standard Library Documentation
- My Python Argparse Cookbook – examples parsing command-line arguments
- My Python Date Formatting — examples working with Python dates.
Formatting Numbers for Printing in Python
Hey there, and welcome to another Python snippet post. Let’s take a look at how to print formatted numbers. We’ll cover rounding, thousands separators, and percentages.
Before we dive in, here’s a quick image overview:
String formatting is actually a surprisingly large topic, and Python has its own internal mini language just for handling the many formatting options available to us. Here we’re just going to focus on a few examples involving numbers, but there is a great deal more to explore.
Format numbers rounded to certain decimal places
First let’s take a look at formatting a floating point number to a given level of precision. There are two ways we can do this: we can specify how many significant figures we want overall, or we can specify how many significant figures we want after the decimal point. Let’s start with the former.
To specify a level of precision, we need to use a colon ( : ), followed by a decimal point, along with some integer representing the degree of precision. We place this inside the curly braces for an f-string, after the value we want to format. You can also use the format method instead, which I’ll demonstrate below.
x = 4863.4343091 # example float to format print(f"") # f-string version print("".format(x)) # format method version
In both cases we get the same result: 4863.43 .
As we can see, our very long float got shortened down to just 6 figures. An interesting thing to note is that this formatting operation actually performs rounding, so if x had a value of 4863.435 , the number printed would actually be 4863.44 . This uses bankers’ rounding (explained here).
If we specify fewer figures than we have in the integer portion of the float, we end up with an exponent representation instead:
x = 4863.4343091 print(f"") # 4.86e+03
4.86e+03 means 4.86 x 10³ , or 4.86 x 1000 , which is 4860 . Looking at this result, we see that we got three significant figures, as we requested.
So how do we specify 3 decimal places? We just need to add an f .
x = 4863.4343091 print(f"") # 4863.434
f indicates that we want our float displayed as a «fixed point number»: in other words, we want a specific number of digits after the decimal point. We can use f on its own as well, which defaults to 6 digits of precision:
x = 4863.4343091 print(f"") # 4863.434309
Display separator character between thousands
For large numbers we often write a separator character (usually a comma, space, or period) to make it easier to read. We can specify this in Python using a comma or underscore character after the colon.
x = 1000000 print(f"") # 1,000,000 print(f"") # 1_000_000
This also works with floats, and the precision formatting, with the comma coming first:
x = 4863.4343091 print(f"") # 4,863.434 print(f"") # 4_863.434
Format floating point numbers as percentages
We can format a number as a percentage by simply adding the percent symbol at the end of our formatting options instead of f :
questions = 30 correct_answers = 23 print(f"You got correct!") # You got 76.67% correct!
When formatting a number as a percentage, the level of precision always refers to the number of digits after the decimal point.
Wrapping Up
That’s it for our very brief dive into formatting numbers. There’s so much more to learn, and we’ll be tackling this in future posts, so make sure to follow us on Twitter to keep up to date with all our content.
We’re also offering our Complete Python Course at its lowest price just for readers of our blog. If you click the link, a coupon will already be applied for you. We’d love to have you, so if you’re looking to upgrade your Python skills, or if you’re just getting started, check it out!
Phil Best
I’m a freelance developer, mostly working in web development. I also create course content for Teclado!