Python 输出格式 [英] Python output formats
问题描述
我有一个搜索输出格式,但格式没有运气.我找不到合适的文档,如果有人能启发我,我真的很想了解这段代码是如何工作的?
Hi there I've had a search output formats and formats had no luck. I couldn't find right documentation for it and I really want to learn how this code works if somebody could enlighten me please?
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%% (我相信一位小数)我真的很难理解这段代码是如何工作的(%%%).如果有人能为我崩溃.
My questions is inside the code % symbols %i %.1f%% (I believe one decimal) I just really struggle understanding this code how it works (%%%) wise. if somebody could break down for me.
输出为:
Survived: 342 (38.4%)
Not Survived: 549 (61.6%)
Total: 891
谢谢.
推荐答案
Python 支持不同的字符串格式化方式.不幸的是,它们在文档中的位置并不相同.所以,我想将它们全部放在一个 SO 答案中是有意义的 :)
Python supports different ways of formatting strings. Unfortunately, they are not all in the same place in the documentation. So, I guess it makes sense to put them all in one SO answer :)
您在问题中的内容是使用模 (%
) 运算符的 printf
样式格式.有关规范,请参阅 printf
-style String Formatting.
What you have in the question is printf
-style formatting using the modulo (%
) operator. For the specification of that see printf
-style String Formatting.
示例:
x = 9
print('value of x is %d' % x)
有关使用 format
函数的格式设置,请参阅 格式字符串语法.
For formatting using the format
function, see Format String Syntax.
示例:
x = 9
print('value of x is {x}'.format(x=x))
相同的语法用作 f-strings 的基础.请参阅 PEP-0498.
The same syntax is used as basis for f-strings. See PEP-0498.
示例:
x = 9
print(f'value of x is {x}')
还有模板字符串,参见模板字符串规范.示例:
There are also template strings, see Template strings specification. Example:
x = 9
print(string.Template('value of x is $x').substitute(x=x))
这篇关于Python 输出格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!