# 方式一: % name = '张三' age = 20 score = 22.556 print('%s的年龄为:%d,成绩%f' % (name, age, score)) # %3s为此处占3个字符位,不够3位前面空位 # %04d为此处占4个字符为,不够4为前面补零 # %.2f为设置保留小数点后两位 print('%3s的年龄为:%04d,成绩%.2f' % (name, age, score)) # 方式二: format() test = '我叫{0},今年{1},请叫我{0}'.format(name, age) print(test) # 模板复用 test1 = '我叫%s,今年%d' data1 = test1 % (name, age) data2 = test1 % ('张三', 18) test2 = '我叫{},今年{}岁' data3 = test2.format(name, age) print(data1) print(data2) print(data3) # 方式三: f'' print(f'我叫{name},今年{age:04d}') # #b转换为二进制,#o 转换为8进制,#x转换为16进制 print(f'我叫{name},今年{age:#b}岁') print(f'我叫{name},今年{age:#o}岁') print(f'我叫{name},今年{age:#x}岁') # 可以为函数返回值,也可以设置占位参数 name1 = 'lily' age1 = 12.223 print(f'我叫{name1.upper()},今年{age1:.2f}岁')
标签:test1,格式化,name,format,Python,age,04d,print,字符串 From: https://www.cnblogs.com/yidaisanhan/p/16979171.html