String formatting agrees to run multiple specific types of substitutions on a string in a single step
Especially when prompted by the user, formatting is very convenient
Implementation method:
1. Formatting expressions, similar to C-voice printf
In an expression, we use the% binary operator
>>> print (' This was%d%s bird '% (1, ' dead ')) This is 1 dead bird
Give the example above (note that the% we are talking about is the same as the one in the middle of the string and the tuple)
Place a string on the left side of%. One or more embedded objects with a% start in the string are placed inside
Put one (or more) on the right of%. Embedded tuples where the objects are inserted into the left translation target location
When multiple objects are inserted. They need to be put into a tuple.
2. Advanced Format expressions
String Formatting code list
Code |
Significance |
S |
String (or whatever object) |
R |
S, but with repr instead of STR |
C |
Character |
D |
Decimal integer |
I |
Integer |
U |
No number integer |
O |
Eight-binary integers |
X |
hexadecimal integer |
X |
X. But print uppercase |
E |
Floating point Index |
E |
E, but print uppercase |
F |
Floating point Decimal |
F |
Floating point Decimal |
G |
Floating point E or F |
G |
Floating point E or F |
% |
constant |
%[(name)][flags][width][.pression]typecode
Sample Example
>>> x=1234>>> res= ' integers:...%d...%-6d...%06d '% (x,x,x) >>> res ' integers: ... 1234...1234
%e,%f,%g There are differences in the printing of floating-point numbers
3. Dictionary-based formatting expressions
To put it bluntly is to give each alternate location a name, so the code looks clearer
Here we are, thank you.
------------------------------------------------------------------
Click the jump 0 Basic python-folder
0 Fundamentals python-7.6 String formatting expressions