How do I print a '%' sign using string formatting?

后端 未结 5 953
孤城傲影
孤城傲影 2020-12-30 20:32

I\'ve made a little script to calculator percent; however, I wish to actually include the \'%\' within the message printed...

Tried this at the start - didn\'t work.

相关标签:
5条回答
  • 2020-12-30 21:07
    x = 0.25
    y = -0.25
    print("\nOriginal Number: ", x)
    print("Formatted Number with percentage: "+"{:.2%}".format(x));
    print("Original Number: ", y)
    print("Formatted Number with percentage: "+"{:.2%}".format(y));
    print()
    

    Sample Output:

    Original Number:  0.25                                                                                        
    Formatted Number with percentage: 25.00%                                                                      
    Original Number:  -0.25                                                                                       
    Formatted Number with percentage: -25.00% 
    

    Helps in proper formatting of percentage value

    +++

    Using ascii value of percentage - which is 37

    print( '12' + str(chr(37)) )
    
    0 讨论(0)
  • 2020-12-30 21:12

    Or use format() function, which is more elegant.

    percent = 12
    print "Percentage: {}%".format(percent)
    

    4 years later edit

    Now In Python3x print() requires parenthesis.

    percent = 12
    print ("Percentage: {}%".format(percent))
    
    0 讨论(0)
  • 2020-12-30 21:21

    The new Python 3 approach is to use format strings.

    percent = 12
    print("Percentage: {0} %\n".format(percent))
    >>> Percentage: 12 %
    

    This is also supported in Python > 2.6.

    See the docs here: Python 3 and Python 2

    0 讨论(0)
  • 2020-12-30 21:24

    format() is more elegant but the modulo sign seems to be quicker!

    http://inre.dundeemt.com/2016-01-13/string-modulo-vs-format-fight/ - shows that modulo is ~30% faster!

    0 讨论(0)
  • 2020-12-30 21:34

    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 %
    
    0 讨论(0)
提交回复
热议问题