3.10. String Formatting (Interactive)¶
This is an interactive tutorial. You can click the rocket -> binder link at the top of this page to interact with the code and outputs below.
3.10.1. Why Format¶
Often string formatting is used to truncate part of a string or round floating point numbers to a desired precision. All of the techniques below use a special shorthand for specifying the formatting desired.
For example:
To round pi to 4 decimal points, we would use the float formatter, f
and specify .4
decimal places. This will round to the number of decimal places specified.
pi = 3.14159265
print("Pi is %.4f" % pi)
Pi is 3.1416
To specify a certain number of characters width, you can also put a number before the decimal point in the format code.
For example:
To print the following lines as 10 characters each, we would specify %10.f
as the format code and Python will automatically add spaced in front to make the output 10 characters long:
print("%10.f" % 1)
print("%10.f" % 10)
print("%10.f" % 100)
print("%10.f" % 1000)
print("%10.f" % 10000)
1
10
100
1000
10000
3.10.2. Three types of string formatting¶
Python allows you to specify how to format strings in 3 ways:
The Old school (% operator):
" "%()
The
.format()
method:" ".format()
With an f-string (Python version > 3.6 only):
f" "
Useful sites:
3.10.3. Old school (%)¶
Below we use the %
operator after the string to include the three elements into the three locations denoted by %
within the string.
We use three different format codes for the three numbers included in the string:
The integer format code
d
The float format code rounding to a whole number
.0f
The float format code rounding to 2 decimal places
.2f
.
Note: To print a regular %, you need to type two %% in a row when using the %
operator.
discount = 30 # %
price = 499.99
new_price = price * (1-discount/100)
print("SALE: Get %d%% off the new PS5 and pay $%.0f instead of $%.2f." %
(discount, new_price, price))
SALE: Get 30% off the new PS5 and pay $350 instead of $499.99.
3.10.4. Format method (.format())¶
The format method inserts each element in the parentheses of .format()
, into the brackets in the string. The same format codes used above are included after the colon in each set of brackets "{:fmt}"
.
print("SALE: Get {:d}% off the new PS5 and pay ${:.0f} instead of ${:.2f}."
.format(discount, new_price, price))
SALE: Get 30% off the new PS5 and pay $350 instead of $499.99.
3.10.5. F-string (f’’)¶
The f-string allows us to include the element in place in the string instead of in a list at the end. This can make it easier to read which values are being inserted into which parts of the string. The syntax is {value:fmt}
with the value being specified before the colon and the format code after the colon in the {}
brackets.
print(f"SALE: Get {discount:d}% off the new PS5 and pay ${new_price:.0f} instead of ${price:.2f}.")
SALE: Get 30% off the new PS5 and pay $350 instead of $499.99.
3.10.6. String formatting with loop¶
We can loop through the following two lists of values and print each pair with a format string.
month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
balance = [-10.45, 50.99, 0.99, -5.76, 100.57, -78.22]
print('Monthly Balance')
for mo, bal in zip(month, balance):
print(f'We have ${bal:.2f} left in {mo}.')
Monthly Balance
We have $-10.45 left in Jan.
We have $50.99 left in Feb.
We have $0.99 left in Mar.
We have $-5.76 left in Apr.
We have $100.57 left in May.
We have $-78.22 left in Jun.
This looks a little messy. We can clean up our output by:
Specifying the width of the number field. Since the longest output is 6 characters, we can use the code
6.2f
to have Python pad all of the numbers to 6 characters longWe can also make a 30-character underline with the
-^30
short hand.
# Monthly Balance is centered on a 30 char line of ---
print('{:-^30}'.format('Monthly Balance'))
for mo, bal in zip(month, balance):
print(f'We have $ {bal:6.2f} left in {mo}.')
# Here we can make a 30 char line of ===
print(f'{"":=^30}')
print('Total balance for the first {} months was $ {:.2f}'.format(len(month), sum(balance)))
-------Monthly Balance--------
We have $ -10.45 left in Jan.
We have $ 50.99 left in Feb.
We have $ 0.99 left in Mar.
We have $ -5.76 left in Apr.
We have $ 100.57 left in May.
We have $ -78.22 left in Jun.
==============================
Total balance for the first 6 months was $ 58.12
3.10.7. Practice: multiplication table¶
Try to exactly reproduce the table below by using a loop, print statements and string format codes.
Note: Pay attention to spacing, zeros in front of the single digit numbers, and the horizontal and vertical lines
01 |02 03 04 05 06 07 08 09
------------------------------------
02 |04 06 08 10 12 14 16 18
03 |06 09 12 15 18 21 24 27
04 |08 12 16 20 24 28 32 36
05 |10 15 20 25 30 35 40 45
06 |12 18 24 30 36 42 48 54
07 |14 21 28 35 42 49 56 63
08 |16 24 32 40 48 56 64 72
09 |18 27 36 45 54 63 72 81
Click the button to reveal ONE of the answers!
import numpy as np
for i in range(1,10):
j = np.arange(1,10)
for idx, ans in enumerate(i*j):
if idx!=8:
print(f'{ans:02d} ', end='')
else:
print(f'{ans:02d} ')
if idx==0:
print('|', end='')
if i == 1:
print('{}'.format('-'*(4*9)) )
# Create your multiplication table here!