当前位置: 首页 > 科技观察

Python格式化字符串的3种方法

时间:2023-03-12 22:36:21 科技观察

前言使用Python的朋友经常会使用打印输出日志进行调试,那么如何格式化输出字符串呢?今天继续给大家分享一点关于Python的小知识。说明我们经常使用%-formatting和str.format()进行格式化,并且从Python3.6开始,增加了f-strings语法,下面我将详细介绍这三种方法。1.%-格式化格式化字符串最早的格式是使用%(百分号),它是这样使用的:In:name='World'In:id='10'In:'Hello%s,id=%s'%(name,id)Out:'HelloWorld,id=10'这里的%s表示格式化为字符串,常用的有%d(十进制整数)和%f(浮点数)。另外还支持字典形式:In:'Hello[%(name)s],id=%(name)s'%{'id':10,'name':'World'}Hello[World],id=102。str.format()格式化字符串一般用法In:name='World'In:'Hello{}'%(name)Out:'HelloWorld'按位置访问:In:'{2},{1},{0}'.format('a','b','c')Out:'c,b,a'通过关键字访问:In:'Hello{name}'.format(name='testerzhang')Out:'Hellotesterzhang'3.f-string格式化字符串Python3.6版本开始出现这种新的格式化字符串,其性能优于前两种方法。In:name="testerzhang"In:print(f'Hello{name}.')In:print(f'Hello{name.upper()}.')Out:Hellotesterzhang.Out:HelloTESTERZHANG.In:d={'id':1,'name':'testerzhang'}In:print(f'User[{d["id"]}]:{d["name"]}')Out:User[1]:testerzhang注意:如果低于Python3.6,可以通过pip安装future-fstrings。这个库不需要在对应的py脚本文件中导入,但是需要在header中添加#coding:future_fstrings。结语因为我现在正在切换到Python3.X版本,所以第三种方法也用的很频繁,不用第二种方法感觉很好。