Why does '%0.0f%%' need a modulus symbol after it in this context?

Question:

Why does ‘%0.0f%%’ need a modulus after it? So far I know that the %0.0f removes all the numbers after the decimal point but what are the two ‘%%’for and why is a modulus required after it? The code by the way is for a histogram using matplotlib.pyplot. I am relatively new to python and seeking a simple explanation.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FormatStrFormatter

data = [0,1,5,9,8,6,7,8,1,2,3,4,5,6,9,8,7,10]
fig, ax = plt.subplots()
counts, bins, patches = ax.hist(data, facecolor='yellow', edgecolor='gray')
print(counts)
 
# Change the colors of bars at the edges...
twentyfifth, seventyfifth = np.percentile(data, [25, 75])
for patch, rightside, leftside in zip(patches, bins[1:], bins[:-1]): 
    if rightside < twentyfifth:  
        patch.set_facecolor('green')
    elif leftside > seventyfifth:         
        patch.set_facecolor('red')
bin_centers = 0.5 * np.diff(bins) + bins[:-1]
print(np.diff(bins))
print(bins[:-1])
for count, x in zip(counts, bin_centers):
    # Label the percentages
    percent = '%0.0f%%' % (100 * float(count) / counts.sum())
    ax.annotate(percent, xy=(x, 0), xycoords=('data', 'axes fraction'),
        xytext=(0, -32), textcoords='offset points', va='top', ha='center')

# Give ourselves some more room at the bottom of the plot    
plt.subplots_adjust(bottom=0.2)
plt.show()

Thanks for your help!

Asked By: TaterTots'

||

Answers:

When using printf style formatting in python, if you want to represent the literal % percent sign, it needs to be escaped by another percent sign. Just like when you want to represent a backslash you need to use a double backslash.

The final %, the one that is written outside of the quotation marks is the operator for the printf style formatting. It basically is a token that indicates that whatever immediately follows is the value that needs to be formatted and injected into the string according the the format specifier.

>>> "Percent %0.0f%%" % 15.1234
'Percent 15%'
>>> "Percent %0.0f%" % 15.1234
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: incomplete format
>>> 

As you can see trying to just use a single % at the end raises a ValueError

However, this isn’t necessary when using f-string style formating, or the string .format method.

>>> f"Percent {15.1234:0.0f}%"
'Percent 15%'
>>> 'Percent {0:0.0f}%'.format(15.1234)
'Percent 15%'

When you aren’t using any formatting at all it also is not neccessary.

>>> 'Percent 15%%'
'Percent 15%%'
>>> 'Percent 15%'
'Percent 15%'
Answered By: Alexander
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.