2500 字全方面解读 Python 的格式化输出

作者 | 欣一
来源 | Python爱好者集中营
今天小编来和大家聊聊Python当中的格式化输出,希望会对大家所有帮助
%占位符的使用
country_ = "France"
currency_ = "Euro"
print("%s is the currency of %s" % (currency_, country_))
Euro is the currency of France
%s之外,代表的是字符串,还有%f代表的是浮点数以及%d代表的是整数,我们来看下面的这个例子,name = '欣一'
age = 24
height = 1.88
print('我是:%s, 年龄:%d, 身高:%fm' % (name,age,height))
我是:欣一, 年龄:24, 身高:1.880000m
2位小数,代码如下print('我是:%s, 年龄:%d, 身高:%.2fm' % (name,age,height))
我是:欣一, 年龄:24, 身高:1.88m
## 左填充
display('%10s' % ('欣一'))
## 右填充
display('%-10s' % ('欣一'))
' 欣一'
'欣一 '
f-string格式化
country_ = "France"
currency_ = "Euro"
print(f"{currency_} is the currency of {country_}")
Euro is the currency of France
f-string格式化的方法好就好在可以直接使用变量名来填充句子当中的内容,当然我们也可以拿它直接来进行数值运算,代码如下print(f'计算结果是:{2*10 + 3*15}')
65
Python当中的内置函数以及lambda方法联用,代码如下string_test = 'Python is awesome'
print(f'我想说 {string_test.lower()}')
我想说 python is awesome
a = 100
b = 10
print(f'计算的结果是:{(lambda x,y:x+y)(a,b)}')
计算的结果是:110
format关键字
format关键字来格式化输出字符串有多种方式,不指定位置
print('我是:{}, 年龄:{}, 身高:{}m'.format (name,age,height))
我是:欣一, 年龄:24, 身高:1.88m
指定位置
print('我是:{0}, 年龄:{1}, 身高:{2}m'.format (name,age,height))
print('我是:{0}, 年龄:{1}, 身高:{1}m'.format (name,age,height))
print('我是:{0}, 年龄:{2}, 身高:{1}m'.format (name,age,height))
我是:欣一, 年龄:24, 身高:1.88m
我是:欣一, 年龄:24, 身高:24m
我是:欣一, 年龄:1.88, 身高:24m
关键字配对
print('我是:{name}, 年龄:{age}, 身高:{height}m'.format(name='欣一', age=25, height=1.88))
我是:欣一, 年龄:25, 身高:1.88m
字典参数
dic = {'name':'欣一','age':24,'height':1.88}
print('我是:{name}, 年龄:{age}, 身高:{height}m'.format(**dic))
我是:欣一, 年龄:24, 身高:1.88m
列表参数
foods = ['fish', 'beef', 'fruit']
s = 'i like eat {} and {} and {}'.format(*foods)
print(s)
i like eat fish and beef and fruit
foods = ['fish', 'beef', 'fruit']
s = 'i like eat {2} and {0} and {1}'.format(*foods)
print(s)
i like eat fruit and fish and beef
精度
pi = 3.1415926
print("{:.2f}".format(pi)) # 保留两位小数
print("{:+.3f}".format(pi)) # 带符号保留3位小数
print("{:.2%}".format(pi)) # 百分比保留两位小数
3.14
+3.142
314.16%
千分位分隔符
print('{:,}'.format(100000000))
100,000,000
print('${:,}'.format(100000000))
$100,000,000


分享

点收藏

点点赞

点在看
关注公众号:拾黑(shiheibook)了解更多
[广告]赞助链接:
四季很好,只要有你,文娱排行榜:https://www.yaopaiming.com/
让资讯触达的更精准有趣:https://www.0xu.cn/
关注网络尖刀微信公众号随时掌握互联网精彩
赞助链接
排名
热点
搜索指数
- 1 中法友谊蕴山水 7904189
- 2 又一个万亿城市来了 7808979
- 3 张荣恭:敢宣布“台独”大陆立刻动手 7713051
- 4 盘点2025大国重器新突破 7617854
- 5 少拿500多休5天 员工全票通过 7522994
- 6 老干妈不需要创新 7427117
- 7 美军承认:击落美军战机 7327789
- 8 尖叫之夜直播 7235467
- 9 地铁回应女子打翻奶茶用围巾擦净 7136107
- 10 流感超过一周还有传染性吗 7045661







AI100
