1、关于三种格式化操作的横向比较
名称 | 描述 | Python版本兼容 | 运行效率 |
---|---|---|---|
% | Python支持的格式化标识符 | 兼容Python2和python3 | 一般 |
format | Python支持的格式化标识符 | python >=2.6 | 一般 |
f | Python支持的格式化标识符 | python >=3.6 | 最快 |
2、使用"%"进行指定位数的数字字符串生成方式
from random import randint
# 使用%生成4位随机数字
code_4 = '%04d' % randint(0, 9999)
# 使用%生成6位随机数字
code_6 = '%06d' % randint(0, 999999)
3、使用format进行指定位数的数字字符串生成方式
from random import randint
# 使用%生成4位随机数字
code_4 = ':0^4'.format(randint(0, 9999))
# 使用%生成6位随机数字
code_6 = ':0^6'.format(randint(0, 999999))