扩展:
保留几位小数
保留两位小数
a = 12345.2487
print('%.2f' % a)
12345.25
保留三位小数
a = 12345.2487
print('%.3f' % a)
12345.249
一、占位符格式化输出
1.1 %s
%s可以接收任意类型的变量
name = 'sean'
age = 50
print('my name is %s,my age is %s.' % (name, age)) # 利用占位符格式化输出
my name is sean,my age is 50.
# 尝试调换括号里面的数值
print('my name is %s,my age is %s.' % (age, name))
my name is 50,my age is sean. # 发现结果也更改了
1.2 %d
%d只能接受数字类型的变量
# 尝试接受字符串类型的变量
name = input('请输入你的名字:')
age = input('请输入你的年龄:')
print('my name is %d, my age is %d.' % (name, age))
请输入你的名字:kody
请输入你的年龄:21
Traceback (most recent call last):
File "G:/python项目/test/test.py", line 5, in <module>
print('my name is %d, my age is %d.' % (name, age))
TypeError: %d format: a number is required, not str
# 发现上面的接受字符串失败,再次尝试接受数字
name = 101
age = 21
print('my name is %d, my age is %d.' % (name, age))
my name is 101, my age is 21. # 没有报错
二、.format()方式
name = input('请输入你的名字:')
age = input('请输入你的年龄:')
print('my name is {},my age is {}.'.format(name, age))
my name is kody,my age is 21.
# 尝试更换后面的name和age位置,看前面传入的值是否会调换位置
print('my name is {},my age is {}.'.format(age, name))
my name is 21,my age is kody. # 值得位置确实调换了
# 思考,如何让值得位置不受name和age接收的限制?
print('my name is {names},my age is {ages}.'.format(ages=age, names=name))
请输入你的名字:kody
请输入你的年龄:21
my name is kody,my age is 21.
三、f-string
python3.6以后才有的新特性
name = input('请输入你的名字:')
age = input('请输入你的年龄:')
print(f'my name is {name}, my age is {age}.')
请输入你的名字:kody
请输入你的年龄:21
my name is kody, my age is 21.