>>> a='1'
>>> b='2','3'
>>> print "%s,%s" % (a,b)
1,('2', '3')
>>> print "%s" % b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
>>> print "%s" % (b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
如上所示,print "%s,%s" % (a,b)
时能把元组b格式化成字符串,而在print "%s" % (b)
中却出现了typeError却没有问题,请问是什么原因?
PS:用列表b进行两种操作都是成功的
要这么写
print "%s, %s" % b
%
操作符的第二个操作对象如果不是一个元组,那么它就只格式化一个值,否则它尝试把元组里每个值都单独格式化。你不可以同样是给它一个元组,有些时候要它当成多个值来格式化,另一些时候又把它当成单一的要格式化的值。
实在不习惯可以用 str
的 .format
方法代替。
另外,(b)
不是只包含一个元素 b
的元组,那个括号只是用于提升表达式的优先级,就像 (1 * 2) + 3
和 (2,) + 3
不一样类似。
>>>b
>>>('2'.'3')
>>>print "%s" % b
相当于
>>>print "%s" % ('2','3')
后面括号里的参数了呀~
print "%s" % (b,)
你要搞懂Python什么脾气。