This article introduces Python string formatting. There are two main methods. I will share it with you. The details are as follows
It is used for string splicing, with better performance.
There are two ways to format strings: percent sign method and format method.
The percent sign method is relatively old, while the format method is relatively advanced, trying to replace the ancient method. Currently, the two coexist.
1. Percent sign method
Format: %[(name)][flags][width].[precision]typecode
- (name) Optional, used to select the specified key
- flags Optional, the available values are:
- + Right aligned: plus positive sign for positive numbers, plus negative sign for negative numbers
- -Left alignment: There is no negative sign before a positive number, and negative sign before a negative number
- width Optional, occupying width
- .precision Optional, the number of digits retained after the decimal point
- typecode Required
- s, get the return 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 passed object and format it to the specified location
- c, integer: converts a number into the value corresponding to its unicode, with a decimal range of 0 <= i <= 1114111
- o, convert integers into octal representations and format them to the specified location
- x, convert integers into hexadecimal and format them to the specified position
- d, convert integers and floating-point numbers into decimal representations 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 method,
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 to everyone's study and I hope everyone will support me more.