简体   繁体   中英

Why are “percent” and “%” not printed in this Python code ? How can I fix it?

The following does not display "%" and "percent" as expected:

def percent (birds,counted):
    percent =  (birds/counted)*100
    return percent


counted = 10
birds= 5
print ("sparrows ", birds,"=",("{:.2f}".format(percent(birds,counted),"percent")))
print ( birds," sparrows = ",("{:.2f}".format(percent(birds,counted) , ("%"))))

How can I get these to show?

To print the % sign you need to 'escape' it with another % sign:

percent = 12
print("Percentage: %s %%\n" % percent)  # Note the double % sign
>>> Percentage: 12 %

You can include the percent symbol or text in your string, like so:

counted = 10
birds= 5
print ("sparrows ", birds,"=",("{:.2f} percent".format(percent(birds,counted))))
print ( birds," sparrows = ",("{:.2f}%".format(percent(birds,counted))))

You need to have enoughs places in your strings if you wish to have all arguments consumed by .format , ie

def percent (birds,counted):
    percent = (birds/counted)*100
    return percent

counted = 10
birds= 5
print ("sparrows ", birds,"=",("{:.2f}{}".format(percent(birds,counted),"percent")))
print ( birds," sparrows = ",("{:.2f}{}".format(percent(birds,counted) , ("%"))))

output:

sparrows  5 = 50.00percent
5  sparrows =  50.00%

I also suggest taking look at so-called f-string if you are working with python 3.6 or newer.

try this one, I hope this will help you.

def percent(birds, counted):
    birds = int(birds)
    counted = int(counted)
    percentage = '{0:.2f}'.format((birds / counted * 100))
    return percentage

birds= 5
counted = 10
print("sparrows", birds, "=", percent(birds, counted), "percent")
print(birds, "sparrows","=", percent(birds, counted), "%")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM