问题
How can I print out the character "%" in the print function. The following line fails.
print "The result is %s out of %s i.e. %d %" % (nominator, denominator, percentage)
回答1:
You must escape the %
by doing %%
. So in your example, do:
print "The result is %s out of %s i.e. %d %%" % (nominator, denominator, percentage)
# ^ extra % to escape the one after
回答2:
Consider using format:
>>> n=23.2
>>> d=1550
>>> "The result is {:.2f} out of {:.2f} i.e. {:.2%}".format(n,d,n/d)
'The result is 23.20 out of 1550.00 i.e. 1.50%'
>>> "The result is {:,.2f} out of {:,.2f} i.e. {:.2%}".format(n,d,n/d)
'The result is 23.20 out of 1,550.00 i.e. 1.50%'
If your arguments are strings:
>>> "The result is {:,.2f} out of {} i.e. {:.2%}".format(n,str(d),n/d)
'The result is 23.20 out of 1550 i.e. 1.50%'
来源:https://stackoverflow.com/questions/19738739/print-special-characters