你好,我搜索过输出格式,但格式没有成功。我找不到合适的文档,我真的想了解这段代码是如何工作的,如果有人可以启发我吗?
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))
我的问题是在代码 % 符号 %i %.1f%% (我相信一位小数)内,我真的很难理解这段代码它是如何工作的(%%%)。如果有人能为我崩溃。
输出是:
Survived: 342 (38.4%)
Not Survived: 549 (61.6%)
Total: 891
谢谢。
Python 支持不同的字符串格式化方式。不幸的是,它们并不都位于文档中的同一位置。所以,我想把它们全部放在一个答案中是有意义的:)
你的问题是printf
使用模 (%
) 操作员。其规格请参见printf-style 字符串格式 https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting.
Example:
x = 9
print('value of x is %d' % x)
对于格式化使用format
函数,参见格式化字符串语法 https://docs.python.org/3/library/string.html#format-string-syntax.
Example:
x = 9
print('value of x is {x}'.format(x=x))
相同的语法用作 f 字符串的基础。看PEP-0498 https://www.python.org/dev/peps/pep-0498/.
Example:
x = 9
print(f'value of x is {x}')
还有模板字符串,参见模板字符串规范 https://docs.python.org/3/library/string.html#template-strings。
例子:
x = 9
print(string.Template('value of x is $x').substitute(x=x))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)