【问题标题】:Python output formatsPython 输出格式
【发布时间】:2021-02-12 04:34:52
【问题描述】:

您好,我搜索过输出格式,但格式没有运气。我找不到正确的文档,如果有人能启发我,我真的很想了解这段代码是如何工作的?

    print ("Survived: %i (%.1f%%)"%(len(survived), float(len(survived))/len(train)*100.0))
print ("Not Survived: %i (%.1f%%)"%(len(not_survived), float(len(not_survived))/len(train)*100.0))
print ("Total: %i"%len(train))

我的问题在代码中 %symbol %i %.1f%%(我相信一位小数)我真的很难理解这段代码是如何工作的(%%%)。如果有人可以为我崩溃。

输出是:

Survived: 342 (38.4%)
Not Survived: 549 (61.6%)
Total: 891

谢谢。

【问题讨论】:

标签: python python-3.x printing


【解决方案1】:

Python 支持格式化字符串的不同方式。不幸的是,它们在文档中并不都在同一个位置。所以,我想将它们全部放在一个 SO 答案中是有意义的 :)

您的问题是使用模 (%) 运算符的printf 样式格式。有关该规范,请参阅printf-style String Formatting

例子:

x = 9
print('value of x is %d' % x)

有关使用format 函数的格式设置,请参阅Format String Syntax

例子:

x = 9
print('value of x is {x}'.format(x=x))

使用相同的语法作为 f 字符串的基础。见PEP-0498

例子:

x = 9
print(f'value of x is {x}')

还有模板字符串,见Template strings specification。 示例:

x = 9
print(string.Template('value of x is $x').substitute(x=x))

【讨论】:

  • 感谢您的回答。感谢您宝贵的时间。这让我更清楚了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-04
  • 2014-01-29
  • 2013-05-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多