Python 的格式化输出

Python提供了两种字符串格式化输出方案,一种是沿袭了C语言的风格,使用  % 占位符输出,还有一种是使用 format 函数。

% (占位符输出)

格式:%[(key)][flags][width][.precision]typecode

例如:

>>> "%(key)s=%(value)d" % dict(key='a', value=10)
'a=10'

常用的占位符有:%s, %d, %f 等,这个和C语言中的占位符一致。另外还可以对输出作对齐和填充。

>>> '[%-10s]' % 'a'  # 左对齐
'[a         ]'
>>> '[%+10s]' % 'a'  # 右对齐
'[         a]'
>>> '%+d, %+d' % (10, -10)  # 带符号位
'+10, -10'
>>> '%010d' % 3  # 用0填充
'0000000003'
>>> '%#x, %o' % (100, 200)  # 以十六进制、八进制输出
'0x64, 310'

format 输出

使用占位符输出能满足数值和字符型两种数据类型的输出,但 format 除了支持这两种类型外,还支持更多的数据类型,包括列表、字典、对象成员等。

格式:'{}'.format()   # 花括号内是格式化规则,圆括号内是被格式化的内容

实际上format的使用方法和 %类似,它采用 . 进行分隔,点号前半部分'{}'是要格式化的规则,点号后半部分format()被格式化的内容。如:

>>>> '{:0>8}'.format('183') # 0表示填充的内容,8是宽度
'00000183'

>>> '[{0:<10}], [{0:^10}], [{0:*>10}]'.format('a') # > 表示右对齐,< 表示左对齐,^ 是居中对齐'[a         ], [    a     ], [*********a]'
>>> '{:.2f}'.format(321.4231) # 使用精度
'321.42'
>>> '{:,}'.format(12394834) # 使用千分位
'12,394,834'
>>> "{0:d} - {0:x} - {0:o} - {0:b} ".format(21) # d是十进制,x是十六进制,o是八进制,b是二进制
'21 - 15 - 25 - 10101 '


>>> 'glazed with {} water beside the {} chickens'.format('rain', 'white') # {} 为空时,直接使用format()内的内容
'glazed with rain water beside the white chickens'
>>> '{0} is better than {1}'.format('emacs', 'vim') # 使用数字时,指定format() 内的变量位置
'emacs is better than vim'
>>> '{1} is better than {0}'.format('emacs', 'vim')
'vim is better than emacs'
>>> " I {verb} the {object} off the {place} ".format(verb="took", object="cheese", place="table") # 可以在{}指定 format()内变量名参数
' I took the cheese off the table '
>>> "Oh {0}, {0}! wherefore art thou {0}?".format("Romeo") # 重复使用一个参数
'Oh Romeo, Romeo! wherefore art thou Romeo?'


>>>email_f = "Your email address was {email}".format  

>>>print(email_f(email='jeff_nie@g.cn')) # 将格式作为一个函数的应用
Your email address was jeff_nie@g.cn


>>> import sys
>>> '{0.platform}'.format(sys) # 应用在对象成员上
'win32'
>>> '{0[b]}'.format(dict(a=10, b=20)) # 应用在字典上
'20'
>>> '[{0[b]}], [{0[a]}]'.format(dict(a=10, b=20)) # 注意在使用多组格式时,使用[]分隔
'[20], [10]'
>>> '{0[5]}'.format(range(10)) # 应用在列表上
'5'

 

不得不说,format 很好很强大!

以上参考:《Python 学习笔记》,http://youngsterxyf.github.io/2013/01/26/python-string-format/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值