Table 3.1. String Formatting code
| format |
Description |
| %% |
Percent percent sign% |
| %c |
Characters and their ASCII code |
| %s |
String |
| %d |
Signed integer (decimal) |
| %u |
unsigned integer (decimal) |
| %o |
unsigned integer (octal) |
| %x |
unsigned integer (hexadecimal) |
| %x |
unsigned integer (16 uppercase characters) |
| %e |
Floating-point numbers (scientific notation) |
| %E |
Floating-point numbers (scientific notation, E instead of e) |
| %f |
Floating point number (with decimal point symbol) |
| %g |
Floating-point numbers (%e or%f depending on the size of the value) |
| %G |
Floating-point numbers (similar to%g) |
| %p |
Pointer (memory address of the value printed in hexadecimal) |
| %n |
Stores the number of output characters into the next variable in the parameter list |
#a tuple is used to pass multiple values to a template, each of which corresponds to a format character. A ="I ' m%s. I ' m%d year old"% ('Vamei', 99)Print(a)#You can also use dictionaries to pass real valuesPrint("I ' m% (name) s. I ' m% (age) D- old"% {'name':'Vamei',' Age': 99})
The format can be further controlled in the following ways:
%[(name)][flags][width]. [Precision]typecode
(name) is named
Flags can have +,-, ' or 0. + Indicates right alignment. -Indicates left alignment. ' is a space that fills a space on the left side of a positive number to align with a negative number. 0 means using 0 padding.
Width indicates display widths
Precision indicates the precision after the decimal point
Like what:
Print ("%+10x") print ("%04d"% 5) print ("%6.3f"% 2.3)
The width above, precision is two integers. We can use * to dynamically substitute these two quantities. Like what:
Print ("%.*f"% (4, 1.2))
Python actually replaces * with 4来. So the actual template is "%.4f".
The built-in% operator in Python can be used to format string operations and control the rendering format of strings. There are other ways to format strings in Python, but the use of the% operator is most convenient.
Reference:
Vamei
Python Learning string formatting