格式化输出字符串
格式化输出字符串主要有两种方式,
1、使用%的字符串输出格式
格式化的输出形式是:字符串%数据
字符串中数据转换格式如下表:
%s | 字符串 |
---|---|
%d | 十进制整数 |
%x | 十六进制整数 |
%o | 八进制整数 |
%f | 十进制浮点数 |
%e | 以科学计数法表示的浮点数 |
%g | 十进制或者科学计数法表示的浮点数 |
可以对比以下方式使用:
#%[域宽.字符宽度]s
#域宽为正是右对齐,为负是左对齐
>>> "Student's name:%10.4s Math score:%10.4f English:%10d"%('Tom',63.2,100)
"Student's name: Tom Math score: 63.2000 English: 100"
>>>"Student's name:%-10.4s Math score:%-10.4f English:%-10d"%('Tom',63.2,100)
"Student's name:Tom Math score:63.2000 English:100 "
2、使用{}和fomate的新式格式化字符串
最简单的使用方法是:
>>>'No.{} No.{} No.{}'.format(1, 2, 3)
'No.1 No.2 No.3'
可以按指定顺序输出,0代表第一个参数,1代表第二个参数,依次类推:
>>>'No.{1} No.{0} No.{2}'.format(1, 2, 3)
'No.2 No.1 No.3'
可以通过命名变量指定顺序输出:
>>>'He is {name},he from {country},he is {old} years old.'.format(name = 'Tom', country='USA',old = 20)
'He is Tom,he from USA,he is 20 years old.'
还可以通过字典指定顺序输出:
>>> Student = {'name':'Tom', 'country':'USA', 'old':20}
#字典Student是第一个参数,所以0代表字典Student
>>>'He is {0[name]},he from {0[country]},he is {0[old]} years old.'.format(Student)
'He is Tom,he from USA,he is 20 years old.'
#还可以增加其他参数
>>>'He is {0[name]},he from {0[country]},he is {0[old]} years old.{1}'.format(Student,'We are friends.')
'He is Tom,he from USA,he is 20 years old.We are friends.'
新输出格式使用“:”来设置输出版式:
#用“<”,“>”和“^”来设置左对齐,右对齐和居中对齐
>>>print('{0:<20d}\n{1:>20.4f}\n{2:^20.4s}'.format(100,12.12345,'abcdefg'))
100
12.1235
abcd
d,f,s依旧指代十进制整数,十进制浮点数,字符串。20代表域宽,“ . ”后的数字对浮点数代表精度,会四舍五入;对于字符串代表字符宽度,会截断字符串。对于整数不能设置带“.”参数。
最后如果想填充非空格的字符时,可以将它放在紧跟“:”之后,在其他设置格式之前:
>>>print('{0:+<20d}\n{1:*>20.4f}\n{2:%^20.4s}'.format(100,12.12345,'abcdefg'))
100+++++++++++++++++
*************12.1235
%%%%%%%%abcd%%%%%%%%