%格式化字符串
之前一直使用的是%
来格式化字符串,但是有时遇到了需要传递一个元组是,就会出现问题,会报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}
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'
>>>
- %(key)s % {key: value}
>>> print "with %(kwarg)s!" % {'kwarg':sub2}
'with an arg!'
>>>
- {key}.format(key=value)
>>> print 'with {kwarg}!'.format(kwarg=sub1)
with python string!!
>>>
网友评论