python字符串格式化_python字符串格式化

python3中字符串格式化有两种方法:%和format

一、%

在%操作符左侧放置一个需要进行格式化的字符串,这个字符串带有一个或多个嵌入的转换目标,都以%开头,如%s,%d,%f。

在%操作符右侧放置一个对象,这些对象将会插入到左侧想让python进行格式化字符串的一个转换目标的位置上。

案例:>>> 'this is a %s' % 'test'

'this is a test'

>>>

>>> 'shuangji %d.this is a %s' % (666,'test') #右侧有多个值时用括号括起来

'shuangji 666.this is a test'

>>>

>>> '%s--%s--%s' % (666,231.51241,[1,2,3]) #python中任何类型都可以转换为字符串。实例中左侧都是%s,会将右侧中的对象转换为字符串(重新创建)。

'666--231.51241--[1, 2, 3]'

>>>

%左侧通用结构是 %[(name)][flags][width宽度][.precision精度]typecode,-左对齐,+正负号,0补零>>> x=1234

>>> test='%d...%-6d...%06d'%(x,x,x) #-号左对齐。0不足位数补零

>>> test

'1234...1234 ...001234'

>>> x=12.126435787654123 #浮点数的表示方法

>>> '%e|%f|%g'%(x,x,x)

'1.212644e+01|12.126436|12.1264'

>>> '%-6.2f|%06.2f|%+06.1f'%(x,x,x) #6.2表示总有6位数,2位小数

'12.13 |012.13|+012.1'

>>> '%-6.2f|%06.2f|%.*f'%(x,x,4,x) #此处*表示精度,将4给*后,x是替代值

'12.13 |012.13|12.1264'

>>>

>>> '%(a)s %(b)s %(c)s %(d)s' % ({'a':'this','b':'is','c':'a','d':'test'}) #基于字典的格式化,是使用键值的。

'this is a test'

二、format方法>>> 'this {} a {}'.format('is','test') #默认1对1,多1不可,缺1不可

'this is a test'

>>> 'this {1} a {0}'.format('is','test') #{}通过位置找出替换目标及插入的参数

'this test a is'

>>> 'this {x} a {y}'.format(x='is',y='test') #{}通过关键字找出替换目标及插入的参数

'this is a test'

>>> 'this {x} a {0}'.format('is',x='test') #两者都有

'this test a is'

>>>

>>> 'this {1[spam]} test of {0.platform}'.format(sys,{'spam':'is'}) #0表示第一个位置,.platform 表示位置或关键字所引用的对象属性:sys.platform。

'this is test of linux'

>>>

format格式结构{fieldname!conversionflag:formatspec},fieldname表示参数的一个数字位置或关键字,conversionflag可以是r,s,a对应repr/str/ascii内置函数的一次调用,formatspec指定了如何表示该值:字段宽度、对齐方式、补零、小数精度等。冒号后的formatspec组成形式有:[[fill]align对齐方式][sign][#][0][width宽度][.precision精度][typecode]>>> '{0:>10}={1:<10}'.format('test',12.62424) #字段宽度为10个,>右对齐,<左对齐

' test=12.62424 '

>>> import sys

>>> '{0.platform:>10}={1[item]:<10}'.format(sys,dict(item='laptop')) #使用位置.属性的方法替换值

' linux=laptop '

>>>

>>> '{0:.2f}'.format(1/3.0)

'0.33'

>>> '{0:.{1}f}'.format(1/3.0,4) #动态的从参数列表获取精度位数

'0.3333'

>>> '{%.*f}'%(6,1/3.0) #动态的使用%从参数列表获取精度位数

'{0.333333}'

>>>

高级用法>>> msg='this {a} a {b} for python,The No.{c}'.format(**{'a':'is','b':'a','c':1}) #使用字典形式来格式化,必须加入两个 *号和大括号

>>> print(msg)

this is a a for python,The No.1

>>>

>>> msg='this {:s} a {:s} for python,The No.{:d}'.format('is','test',1)

>>> print(msg)

this is a test for python,The No.1

>>>

>>> msg='this {:s} a {:s} for python,The No.{:d}'.format(*['is','test',1]) #列表形式加入一个*号,*表示将列表中的元素,遍历出来,类似上面一个列子

>>> print(msg)

this is a test for python,The No.1

>>>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值