【问题标题】:Anomaly in print statement in python [duplicate]python中的打印语句异常[重复]
【发布时间】:2017-04-05 16:08:37
【问题描述】:

假设我在 python 中有一个print 语句:

print "components required to explain 50% variance : %d" % (count)

这个语句给出了ValuError,但是如果我有这个print 语句:

print "components required to explain 50% variance"

为什么会这样?

【问题讨论】:

  • print "components required to explain 50%% variance : %d" % (count)
  • .format 更复杂,只是提醒一下

标签: python


【解决方案1】:

% 运算符应用于字符串,对字符串中的每个 '%' 执行替换。 '50%' 没有指定有效的替换;要在字符串中简单地包含一个百分号,您必须将其加倍。

【讨论】:

    【解决方案2】:

    错误信息在这里很有帮助:

    >>> count = 10
    >>> print "components required to explain 50% variance : %d" % (count)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: unsupported format character 'v' (0x76) at index 35
    

    所以python看到% v就认为是格式码。但是,v 不是受支持的格式字符,因此会引发错误。

    修复一旦你知道就很明显了——你需要转义不属于格式代码的%s。你是怎样做的?通过添加另一个%:

    >>> print "components required to explain 50%% variance : %d" % (count)
    components required to explain 50% variance : 10
    

    请注意,您也可以使用.format,这在很多情况下更方便、更强大:

    >>> print "components required to explain 50% variance : {:d}".format(count)
    components required to explain 50% variance : 10
    

    【讨论】:

      猜你喜欢
      • 2014-01-02
      • 2017-03-08
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 2020-02-03
      • 1970-01-01
      相关资源
      最近更新 更多