Python output formats

血红的双手。 提交于 2021-02-05 12:24:08

问题


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))

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.

Output is:

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

Thank you.


回答1:


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 :)

What you have in the question is printf-style formatting using the modulo (%) operator. For the specification of that see printf-style String Formatting.

Example:

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

For formatting using the format function, see Format String Syntax.

Example:

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

The same syntax is used as basis for f-strings. See PEP-0498.

Example:

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))


来源:https://stackoverflow.com/questions/64596095/python-output-formats

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!