字符串初始化使用字符串初始化操作符即百分号—% 。
标记转化说明符的开始。
在%左边为格式化字符串,右边为被格式化的值。
>>> format='hello,%s.%s enough?'
>>> values=('world','cold')
>>> print format % values
ld enough?
>>>
格式化字符串的%s部分为转换说明符,他们标记了需要插入转换值的位置。s表示值会被格式化为字符串,如果要格式化实数,用f说明转化说明符的类型,同时需要提供精度:一个句点再加上保留的小数位数。
>>> format='pi with three decimals: %.3f'
>>> from math import pi
>>> print format % pi
pi with three decimals: 3.142
>>>
序列会被解释为一个值,元组和字典可以格式化为字符串。
如果右操作数为元组,每一位元素都会被单独格式化,每一个值都需要一个对应的转化说明符。
>>> '%s plus %s equals %s' % (1,1,2)
1 plus 1 equals 2
>>>
—表示左对齐;+表示在转换值之前要加上正负号 ; “ ”表示正数之前保留空格;0表示转换值若位数不够则用0填充。
>>> from math import pi
>>> '%010.2f' % pi
'0000003.14'
>>> '%-10.2f' % pi
'3.14 '
>>> print ('%5d' % 10 +'n'+'%5d' % -10)10-10
>>> print ('%+5d' % 10 +'n'+'%+5d' % -10)+10-10
>>>
*转换后的字符串应具有指定的宽度。如果是 ,则宽度会从值元组中读出。
*如果转换的是实数,精度值就表示出现在小数点后的位数。如果转换的是字符串,那么该数字就是最大字段宽度。如果是 ,精度从元组中读出来。
>>> from math import pi
>>> '%10.2f' % pi
' 3.14'
>>> '%*.2f' % (10,pi)
' 3.14'
>>> '%*.*f' % (10,2,pi)
' 3.14'
>>> '%.*f' % (2,pi)
'3.14'
>>> '%5.2s' % 'abcdef'
' ab'
>>> '%*.2s' % (5,'abcdef')
' ab'
>>> '%*.*s' % (5,2'abcdef')
' ab'
>>> '%.*s' % (2,'abcdef')
'ab'
>>>
d , i —–带符号的十进制正数
u —–不带符号的十进制
o —–不带符号的八进制
x , X —–不带符号的十六进制
e , E —–科学计数法表示的浮点数
f , F —–十进制浮点数
g , G —–指数大于-4或者小于精度值则和e相同,否则与f相同
c —–单字符(接受整数)
r —–字符串(使用repr转换的对象)
s —–字符串(使用str转换的对象)
>>> 'the number is %d' % 17
'the number is 17'
>>> 'the number is %i' % 17.567
'the number is 17'
>>> 'the number is %o' % 17
'the number is 21'
>>> 'the number is %x' % 17
'the number is 11'
>>> 'the number is %f' % 17.567
'the number is 17.567000'
>>> 'the number is %e' % 17.567
'the number is 1.756700e+01'
>>> 'the number is %g' % 17.567
'the number is 17.567'
>>> 'the number is %g' % 0.0000017567
'the number is 1.7567e-06'
>>> 'the letter is %c' % 'a'
'the letter is a'
>>> 'the letter is %r' % 42l
'the letter is 42L'
>>> 'the letter is %s' % 42l
'the letter is 42'
字符串格式化示例
#使用给定的宽度打印格式化后的价格列表
width=input('please enter width:')price_width=10
item_width=width-price_widthheader_format='%-*s%*s'
format ='%-*s%*.2f'print '='*width
print header_format %(item_width,'item',price_width,'price')print '-' *widthprint format %(item_width,'apples',price_width,0.4)
print format %(item_width,'pears',price_width,0.5)
print format %(item_width,'cantal',price_width,1.92)
print format %(item_width,'dried(16 oz)',price_width,8)
print format %(item_width,'prunes(4 1bs)',price_width,12)
结果如下
>>>======================= RESTART =======================
>>>
please enter width:35
===================================
item price
-----------------------------------
apples 0.40
pears 0.50
cantal 1.92
dried(16 oz) 8.00
prunes(4 1bs) 12.00
>>>
本文发布于:2024-01-31 13:28:43,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170667892628869.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |