【问题标题】:Print special characters打印特殊字符
【发布时间】:2013-11-02 03:42:20
【问题描述】:

如何在打印功能中打印出字符“%”。以下行失败。

print "The result is %s out of %s i.e. %d %" % (nominator, denominator, percentage)

【问题讨论】:

    标签: python printing character percentage


    【解决方案1】:

    您必须通过 %% 转义 %。所以在你的例子中,做:

    print "The result is %s out of %s i.e. %d %%" % (nominator, denominator, percentage)
    #                                         ^ extra % to escape the one after
    

    【讨论】:

    • @SteveP。我其实一点头绪都没有,我想这只是% 转义% 和`\` 撇号
    【解决方案2】:

    考虑使用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%'
    

    如果你的参数是字符串:

    >>> "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%'
    

    【讨论】:

      猜你喜欢
      • 2014-07-27
      • 2014-08-13
      • 1970-01-01
      • 1970-01-01
      • 2020-07-21
      • 2013-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多