1、%用法
整数的输出
%o —— oct 八进制
%d —— dec 十进制
%x —— hex 十六进制
1 >>> print('%o' % 20)
2 24
3 >>> print('%d' % 20)
4 20
5 >>> print('%x' % 20)
6 14
>>> print('%f' % 1.11) # 默认保留6位小数
1.110000
>>> print('%.1f' % 1.11) # 取1位小数
1.1
>>> print('%e' % 1.11) # 默认6位小数,用科学计数法
1.110000e+00
>>> print('%.3e' % 1.11) # 取3位小数,用科学计数法
1.110e+00
>>> print('%g' % 1111.1111) # 默认6位有效数字
1111.11
>>> print('%.7g' % 1111.1111) # 取7位有效数字
1111.111
>>> print('%.2g' % 1111.1111) # 取2位有效数字,自动转换为科学计数法
1.1e+03
使用%号进行字符串的匹配替换
eg:
url = 'https://www.baidu.com %d'
#法一
q = url % 425
print(q)
#法二
print(format(url % 425))
2、相对基本格式化输出采用‘%’的方法,format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’
>>> print('{} {}'.format('hello','world')) # 不带字段
hello world
>>> print('{0} {1}'.format('hello','world')) # 带数字编号,右边的位置下标与左边的{}中的数字一一对应
hello world
>>> print('{0} {1} {0}'.format('hello','world')) # 打乱顺序
hello world hello
>>> print('{1} {1} {0}'.format('hello','world'))
world world hello
>>> print('{a} {tom} {a}'.format(tom='hello',a='world')) # 带关键字
world hello world
举例:
url = 'https://www.baidu.com {a}'
# q = url % 425
# print(q)
# print(format(url % 425))
print(url.format(a=3))
参考
https://www.cnblogs.com/fat39/p/7159881.html#tag1