Details of Python str operation method of

  • 2020-06-07 04:42:15
  • OfStack

str. format() : Format the string with "{}" placeholders (the index-number form and key-value pair form in placeholders can be mixed).


>>> string = 'python{}, django{}, tornado{}'.format(2.7, 'web', 'tornado') #  How many {} A placeholder is a number of values that are "filled" into the string in order 
>>> string
'python2.7, djangoweb, tornadotornado'
>>> string = 'python{}, django{}, tornado{}'.format(2.7, 'web')
Traceback (most recent call last):
 File "<pyshell#6>", line 1, in <module>
  string = 'python{}, django{}, tornado{}'.format(2.7, 'web')
IndexError: tuple index out of range
>>> string = 'python{0}, django{2}, tornado{1}'.format(2.7, 'web', 'tornado') #  You can also specify values to "fill in" (from 0 I'm going to start off with no 1 Use all, but make sure that the specified location has a value) 
>>> string
'python2.7, djangotornado, tornadoweb'
>>> string = 'python{py}, django{dja}, tornado{tor}'.format(tor='tornado', dja='web', py=2.7) #  Assignments can be made in the form of key-value pairs 
>>> string
'python2.7, djangoweb, tornadotornado'
>>>

2. Use "%" for string formatting.

Format symbol table

%c 转为单字符
%r 转为用repr()表达的字符串
%s 转为用str()表达的字符串
%d或%i 转为有符号的10进制整数
%u 转为无符号的10进制整数
%o 转为无符号的8进制整数
%x 转为无符号的106进制整数,106进制字母用小写表示
%X 转为无符号的106进制整数, 106进制字母用大写表示
%e 转为科学计数法表达的浮点数,其中的e用小写表示
%E 转为科学计数法表达的浮点数,其中的E用大写表示
%f或#F 转为浮点数
%g 由Python根据数字的大小自动判断转换为%e或%f
%G 由Python根据数字的大小自动判断转换为%E或%F
%% 输出“%”

Auxiliary formatting symbol table

* 定义宽度或小数点的精度
- 左对齐
+ 对正数输出正值符号“+”
<sp> 数字的大小不足m.n的要求时,用空格补位
# 在8进制数前显示0,在106进制数前显示0x或0X
0 数字的大小不足m.n的要求时,用0补位
m.n m是显示的最小总宽度,n是小数点后的位数(如果可用)


Related articles: