问题
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