The string formatting operator (%) applies only to string types, very similar to the string formatting of the printf () function in C, and even uses the same symbols, with percent sign (%), and supports all printf () format operations. The syntax is as follows:
Format_String% String_to_convert
Format_String is a format-tagged string, in the form "%cdoe"; String_to_convert is a string to be formatted, and if it is more than two, it needs to be enclosed in parentheses.
string formatting symbols
| formatting symbols |
description |
| % c |
converted to a character (ASCII value, or a string of one length) |
| %r |
takes precedence over string conversions with the repr () function (Python2.0 new) |
| %s |
takes precedence over string conversions with the str () function |
| %d/%i |
go to signed decimal number |
| %u |
turns unsigned decimal number |
| %o |
turns unsigned octal number |
| %x /%x |
(Unsigned) turns to unsigned hexadecimal number (x/x represents large
lowercase for converted hexadecimal characters) |
| %e/%e |
to scientific notation (e/e control output e/e) |
| %f/%f |
turn into floating-point numbers (fractional parts naturally truncated) |
Td>%g/%g
| %e and%f/%e and%f abbreviations |
| %% |
output% |
>>> #打印字符串 >>> print (' My name is%s '% ' Rusky ') My name is rusky>>> #打印整数 >>> print (' He i S%d years old '% (in)) He is years old>>> #打印浮点数 >>> print (' His height is%f M '% (1.78)) He height is 1.780000 m>>> print (' His height is%.2f M '% (1.78)) He height is 1.78 m>>> #指定占位符宽度 >>> print ( ' name:%10s age:%8d height:%8.2f '% (' Rusky ', 26,1.78)) Name: Rusky Age: Height: 1.78>>> # Specify placeholder width-left alignment >>> print (' name:%-10s age:%-8d height:%-8.2f '% (' Rusky ', 26,1.78)) Name:rusky age:26 height:1.78
Python string formatting