format用法:
format()功能很强大,它把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’。
使用方法由两种:b.format(a)和format(a,b)。
1、基本用法
(1)不带编号,即“{}”
(2)带数字编号,可调换顺序,即“{1}”、“{2}”
(3)带关键字,即“{a}”、“{tom}”
>>> print('{} {}'.format('千锋','教育')) # 不带字段
千锋 教育
>>> print('{0} {1}'.format('千锋','教育')) # 带数字编号
千锋 教育
>>> print('{0} {1} {0}'.format('千锋','教育')) # 打乱顺序
千锋 教育 千锋
>>> print('{1} {1} {0}'.format('千锋','教育'))
教育 教育 千锋
>>> print('{a} {b} {a}'.format(a='千锋',b='教育')) # 带关键字
千锋 教育 千锋
2、进阶用法
(1)< (默认)左对齐、> 右对齐、^ 中间对齐、= (只用于数字)在小数点后进行补齐
(2)取位数“{:4s}”、"{:.2f}"等
>>> print('{} and {}'.format('千锋','教育')) # 默认左对齐
千锋 and 教育
>>> print('{:10s} and {:>10s}'.format('千锋','教育')) # 取10位左对齐,取10位右对齐
千锋 and 教育
>>> print('{:^10s} and {:^10s}'.format('千锋','教育')) # 取10位中间对齐
千锋 and 教育
>>> print('{} is {:.2f}'.format(1.123,1.123)) # 取2位小数
1.123 is 1.12
>>> print('{0} is {0:>10.2f}'.format(1.123)) # 取2位小数,右对齐,取10位
1.123 is 1.12
3、多个格式化
'b' - 二进制。将数字以2为基数进行输出。
>>> print('{0:b}'.format(3))
11
'c' - 字符。在打印之前将整数转换成对应的Unicode字符串。
>>> print('{:c}'.format(20))
4
'd' - 十进制整数。将数字以10为基数进行输出。
>>> print('{:d}'.format(20))
20
'o' - 八进制。将数字以8为基数进行输出。
>>> print('{:o}'.format(20))
24
'x' - 十六进制。将数字以16为基数进行输出,9以上的位数用小写字母。
>>> print('{:x}'.format(20))
14
'e' - 幂符号。用科学计数法打印数字。用'e'表示幂。
>>> print('{:e}'.format(20))
2.000000e+01
'g' - 一般格式。将数值以fixed-point格式输出。当数值特别大的时候,用幂形式打印。
>>> print('{:g}'.format(20.1))
20.1
'n' - 数字。当值为整数时和'd'相同,值为浮点数时和'g'相同。不同的是它会根据区域设置插入数字分隔符。
>>> print('{:f}'.format(20))
20.000000
>>> print('{:n}'.format(20))
20
'%' - 百分数。将数值乘以100然后以fixed-point('f')格式打印,值后面会有一个百分号。
>>> print('{:%}'.format(20))
2000.000000%
4、通过位置匹配参数
>>> '{0}, {1}, {2}'.format('北京', '千锋', '教育')
'北京,千锋,教育'
>>> '{}, {}, {}'.format('北京', '千锋', '教育') # 3.1+版本支持
'北京,千锋,教育'
>>> '{2}, {1}, {0}'.format('北京', '千锋', '教育')
'教育,千锋,北京'
>>> '{2}, {1}, {0}'.format(*'北京千') # 可打乱顺序
'千, 京, 北'
>>> '{0}{1}{0}'.format('千锋', '教育') # 可重复
'千锋教育千锋'
5、通过名字匹配参数
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
另,可在字符串前加f以达到格式化的目的,在{}里加入对象,此为format的另一种形式:
name = 'qianfeng'
age = 18
sex = 'man'
job = "IT"
salary = 9999.99
print(f'my name is {name.capitalize()}.')
print(f'I am {age:*^10} years old.')
print(f'I am a {sex}')
print(f'My salary is {salary:10.3f}')
# 结果
my name is Qianfeng.
I am ****18**** years old.
I am a man
My salary is 9999.990
【重要消息】感谢知友您能够看到这部分内容,本文是软件测试系列知识中python脚本语言中的一篇,笔者认为本部分全面的知识应该包含如下图所示的内容:
如果知友对这部分内容感兴趣,可以持续关注小编的账号,除此之外,小编还录制了不少这方面的技术视频,知友如果有需要,可以私聊本小编获取哦!