String formatting symbols
Format Character Conversion mode
%c converted to character (ASCII value, or string of length one )
%r takes precedence over string conversions with the repr () function
%s takes precedence over string conversion with the str () function
%d/%i turns into signed decimal number
%u turns into unsigned decimal number
%o Turn unsigned octal number
%x/%x (Unsigned) turns to unsigned hexadecimal number (x/x represents the case of converted 16 characters )
%e/%e turns into scientific notation (e/e control output e/e)
%f/%f into floating-point numbers ( Fractional parts are naturally truncated )
shorthand for %g/%g%e and %f/%e and %f
Before the decimal point is less than 6 bits, the floating point type, a total of six digits, before the decimal point is larger than 6 bits, then the scientific notation, also a total of six bits
% output %
Formatting operator Auxiliary directives
Symbolic effect
* Define width or decimal point accuracy
-Used for left alignment
+ Show plus sign (+) in front of positive number
<sp> show spaces in front of positive numbers
# 0 (' 0 ')is displayed in front of the octal number, preceded by ' 0x ' or ' 0X 'in hexadecimal ( depending on ' x ' or ' X ')
0 The number shown is preceded by ' 0 ' instead of the default space
% ' percent ' output a single '% '
(VAR) mapping variable ( dictionary parameter )
M.N m is the smallest total width displayed , and N is the number of digits after the decimal point ( if available )
Here are some examples of using format Strings :
Hex Output :
>>> "%x"% 108
' 6c '
>>>
>>> "%x"% 108
' 6C '
>>>
>>> "% #X"% 108
' 0x6c '
>>>
>>> "% #x"% 108
' 0x6c '
Floating-point number and scientific notation output :
>>>
>>> '%f '% 1234.567890
' 1234.567890 '
>>>
>>> '%.2f '% 1234.567890
' 1234.57 '
>>>
>>> '%E '% 1234.567890
' 1.234568E+03 '
>>>
>>> '%e '% 1234.567890
' 1.234568e+03 '
>>>
>>> '%g '% 1234.567890
' 1234.57 '
>>>
>>> '%G '% 1234.567890
' 1234.57 '
>>>%.7g '% 1234.567890
' 1234.568 '
>>> '%g '% 123456.7890
' 123457 '
>>> "%e"% (1111111111111111111111L)
' 1.111111e+21 '
Integer and string output :
>>> "%+d"% 4
' +4 '
>>>
>>> "%+d"%-4
'-4 '
>>>
>>> "We are at%d%%"% 100
' We is at 100% '
>>>
>>> ' Your host is:%s '% ' Earth '
' Your host Is:earth '
>>>
>>> ' Host:%s\tport:%d '% (' Mars ', 80)
' Host:mars port:80 '
>>>
>>> num = 123
>>> ' Dec:%d/oct:% #o/hex:% #X '% (num, num, num)
' dec:123/oct:0173/hex:0x7b '
>>>
>>> "mm/dd/yy =%02d/%02d/%d"% (2, 15, 67)
' Mm/dd/yy = 02/15/67 '
>>>
>>> W, p = ' Web ', ' page '
>>> ' http://xxx.yyy.zzz/%s/%s.html '% (W, p)
' Http://xxx.yyy.zzz/Web/page.html '
The parameters of the dictionary type are provided to the format operator .
>>> ' There is% (Howmany) d% (Lang) s quotation Symbols '% {' lang ': ' Python ', ' Howmany ': 3}
' There is 3 Python quotation Symbols '
Format operator (%)