This article mainly introduces the method of Python string format (two kinds), small series feel very good, now share to everyone, also for everyone to do a reference. Let's take a look at it with a little knitting.
This article describes the Python string format, there are two main ways to share to everyone, specifically as follows
For concatenation of strings, the performance is more excellent.
There are two ways to format a string: percent-semicolon, format-mode.
The percent is older, and the format method is more advanced, trying to replace the old way, the present two coexist.
1, percent of the way
Format:%[(name)][flags][width]. [Precision]typecode
(name) optional, used to select the specified key
Flags are optional, and the values to choose from are:
+ Right Alignment: Positive number home plus, negative plus minus
-Left justification: No minus sign before positive number, plus minus sign before negative number
Width selectable, occupied widths
. Precision optional, number of digits retained after the decimal point
TypeCode must choose
S, gets the return value of the passed-in object __str__ method, and formats it to the specified location
R, gets the return value of the __repr__ method of the passed-in object and formats it to the specified location
C, Integer: Converts a number to its Unicode corresponding value, 10 binary range is 0 <= i <=1114111
O, converts an integer to an octal representation and formats it to a specified location
X, converts an integer to 16 and formats it to a specified position
D, converts an integer, floating-point number to a decimal representation, and formats it to a specified position
>>> s = ' I am%s,age%d '% (' cai ', ') >>> print (s) I am cai,age (s) = ' I am% (N1) S,age% (n2) d '%{' N1 ': ' Cai ', ' N2 ':18}>>> print (s) I am cai,age >>> s = ' I am% (N1) +10s,age% (n2) d '%{' N1 ': ' Cai ', ' N2 ' :18}>>> print (s) I am cai,age >>> s = ' I am% (N1) +10s,age% (n2) 10d '%{' N1 ': ' Cai ', ' N2 ':18}>> > Print (s) I am cai,age >>> s = "I am%.3f abcd"%1.2>>> print (s) I am 1.200 ABCD
2. Format mode,
i1 = "I am {},age {}, {}". Format (' Cairui ', ', ' KK ') print (i1) I am cairui,age, kki1 = "I am {0},a GE {1}, {0} ". Format (' Cairui ',") print (i1) I am cairui,age, cairuii1 = "I am {name},age {age}, {name}". Format (name= ' Cai Rui ', age=18) print (i1) I am cairui,age, cairuii1 = "I am {: s},age {:d}, {: F}". Format (' Cairui ', 18,6.1) print (i1) I am CA Irui,age, 6.100000