Python string formatting method (two methods), python string
This article describes how to format Python strings in two ways:
It is used for String concatenation and has better performance.
Two methods are available for string formatting: percent sign and format.
The percent sign method is relatively old, while the format method is relatively advanced. It attempts to replace the old one. Currently, the two methods coexist.
1. percent sign Method
Format: % [(name)] [flags] [width]. [precision] typecode
- (Name) (optional) used to select the specified key
- (Optional) flags. Optional values include:
- + Right alignment: positive signs for positive numbers and negative signs for negative numbers
- -Left alignment: There is no negative number before a positive number, and a negative number before a negative number.
- Width (optional) occupies the width.
- . Precision (optional) number of digits retained after decimal point
- Typecode required
- S, get the returned value of the passed object _ str _ method, and format it to the specified location
- R, get the return value of the _ repr _ method of the input object, and format it to the specified location
- C, integer: converts a number to its unicode value. The value range is 0 <= I <= 1114111.
- O. Convert the integer to octal and format it to the specified position.
- X. Convert the integer to hexadecimal format and format it to the specified position.
- D. Convert the integer and floating point number into decimal format and format them to the specified position.
>>> s = 'i am %s,age %d' %('cai',18)>>> print(s)i am cai,age 18 >>> s = 'i am %(n1)s,age %(n2)d' %{'n1':'cai','n2':18}>>> print(s)i am cai,age 18 >>> s = 'i am %(n1)+10s,age %(n2)d' %{'n1':'cai','n2':18}>>> print(s)i am cai,age 18 >>> s = 'i am %(n1)+10s,age %(n2)10d' %{'n1':'cai','n2':18}>>> print(s)i am cai,age 18 >>> s = "i am %.3f abcd" %1.2>>> print(s)i am 1.200 abcd
2. format,
i1 = "i am {},age {} ,{}".format('cairui',18,'kk')print(i1) i am cairui,age 18 ,kk i1 = "i am {0},age {1} ,{0}".format('cairui',18)print(i1) i am cairui,age 18 ,cairui i1 = "i am {name},age {age} ,{name}".format(name='cairui',age=18)print(i1) i am cairui,age 18 ,cairui i1 = "i am {:s},age {:d} ,{:f}".format('cairui',18,6.1)print(i1) i am cairui,age 18 ,6.100000
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.