python学习(字典使用字符串格式化)

本文介绍了Python中多种字符串格式化的实用方法,包括使用字典、列表、格式化字符串等进行字符串填充、对齐及替换等操作。同时展示了如何通过特定格式设定数值显示精度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串格式化


1.字典字符串格式化
>>> '%(a)s %(b)s' %  {'a':'fruit','b':'apple'}
'fruit apple'


2.>>> hello='''hello %(name)s  !
 your age is %(age)s
 '''
>>> values={'name':'bob','age':25}
>>> print {hello%values}
set(['hello bob  !\n your age is 25\n '])


3.food='i like eat {0},{fruit} and {1}'
>>> food.format('eggs','apple',fruit='pear')
'i like eat eggs,pear and apple'


4.package='{tuple},{0} and {list}'.format('python',tuple='123',list=[1,2,3])
>>>package.split('and')
['123,python ', ' [1, 2, 3]']


>>> package.replace('python','is not equl')
'123,is not equl and [1, 2, 3]'


5.>>> import sys
>>> 'my {1[os]} runs {0.platform}'.format(sys,{'os':'win'})
'my win runs win32'




>>> 'my {config[os]} runs {s.platform}'.format(s=sys,config={'os':'win'})
'my win runs win32'


6.>>> slist=list('spam')
>>> parts=slist[0],slist[1],slist[1:3]  #列表分片半开半闭
>>> '{0},{1},{2}'.format(*parts)
"s,p,['p', 'a']"


7.>>> '{0:>10}={1:<10}'.format('bob',123.123)       #左对齐
'       bob=123.123   '                 


8.>>> '{0.platform} is {1[os]}'.format(sys,dict(os='win'))
'win32 is win'


9.
>>> bin(255),int('11111111',2),0b11111111
('0b11111111', 255, 255)
>>> hex(255),int('FF',16),0xFF
('0xff', 255, 255)
>>> oct(255),int('377',8),0o377,0377
('0377', 255, 255, 255)


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


>>> '{0:.{1}f}'.format(1/3.0,4)
'0.3333'
>>> '%.*f' % (4,1/3.0)   # 利用‘’*f‘’先取%右边第一个为width参数
'0.3333'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值