Python字符串格式化%And.format -03

2017-03-18  本文已影响24人  嘿嘿_小于同学

%格式化字符串

之前一直使用的是%来格式化字符串,但是有时遇到了需要传递一个元组是,就会出现问题,会报TypeError的错误。

>>> name = (1,2,3)
>>> print 'My name is %s!' % name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
>>>

为了保证正常使用,即使只有一个变量,也使用元组存放。

>>> name = (1,2,3)
>>> print 'My name is %s!' % (name, )
My name is (1, 2, 3)!

.format格式化字符串

num表示参数的位置{0}表示第一个占位符

>>> sub1 = 'python string!'
>>> sub2 = 'an arg'
>>> a = 'with {0}'.format(sub1)
>>> a
'with python string!'
>>> b = 'with {0}, with {1}'.format(sub1, sub2)
>>> b
'with python string!, with an arg'
>>>
>>> print "with %(kwarg)s!" % {'kwarg':sub2}
'with an arg!'
>>>
>>> print 'with {kwarg}!'.format(kwarg=sub1)
with python string!!
>>>
上一篇下一篇

猜你喜欢

热点阅读