python 格式化输出

python 中有三种格式化输出方式


1、占位符 %s %d %f
%s 代表的是字符串,%d 代表的是整数,%f代表的是浮点数

点击查看代码
name = '小红'
age = 12
money = 1.01
print('我的名字是%s, 我今年%d岁了,我有%f元钱' %(name, age, money))

# 输出结果为:
我的名字是小红, 我今年12岁了,我有1.010000元钱

注意这个地方输出的money是1.010000,因为%f默认保留六位小数
可以使用%m.nf 这种表示方式,m表示整数位数+小数位数,n表示小数位数
例如:
print('我的名字是%s, 我今年%d岁了,我有%3.2f元钱' %(name, age, money))
输出结果为我的名字是小红, 我今年12岁了,我有1.01元钱


2、{} 占位符 + format()方法,该种方式不用考虑数据类型
(1)不带编号,即"{}"
(2)带数字编号,可调换顺序,即"{1}"、"{2}"
(3)带关键字,即"{name}"、"{age}"

点击查看代码
 1 >>> print('{} {}'.format('hello','world'))  # 不带字段
 2 hello world
 3 >>> print('{0} {1}'.format('hello','world'))  # 带数字编号
 4 hello world
 5 >>> print('{0} {1} {0}'.format('hello','world'))  # 打乱顺序
 6 hello world hello
 7 >>> print('{1} {1} {0}'.format('hello','world'))
 8 world world hello
 9 >>> name = Tonny
   >>> age = 18
   >>> print('我的名字是{name},我的年龄是{age}'.format(name,age))  # 带关键字


3、print(f'{} {}'),这种方式和第二种类似

点击查看代码
name = '小红'
age = 12
print(f'我的名字是{name}, 我的年龄是{age}')

# 输出结果为
我的名字是小红, 我的年龄是12
posted @ 2024-03-14 16:02  有形无形  阅读(37)  评论(0)    收藏  举报