为什么我在格式化元组时会出现"TypeError: not all arguments converted during string formatting"错误?
我想用 %
风格的字符串格式化来打印一个元组:
tup = (1,2,3)
print("this is a tuple: %s." % (tup))
我希望它能打印出 这是一个元组: (1,2,3).
,但我却收到一个错误,内容是 TypeError: not all arguments converted during string formatting
。
这是什么问题,我该怎么解决呢?
在编辑这个问题以使其更清晰和现代化时,我保留了原始例子中的一个有趣之处:围绕 tup
的括号。这些括号对于 %
语法来说 并不是必要的,而且 也不会创建一个元组。可能提问者认为括号是必须的,但实际上搞错了。关于这个问题的更多信息,可以查看 如何创建一个只有一个元素的“单例”元组。
12 个回答
54
正确的做法是:
>>> thetuple = (1, 2, 3)
>>> print("this is a tuple: %s" % (thetuple,))
this is a tuple: (1, 2, 3)
在Python 3.x中,%
这个字符串操作符仍然可以使用,它让你把元组(或列表)中的值格式化得更简单。用.format
来处理这种情况会需要额外的工作——要么把值作为单独的参数传入,要么需要给序列加上索引:
>>> tup = (1,2,3)
>>> print("First: %d, Second: %d, Third: %d" % tup)
First: 1, Second: 2, Third: 3
>>> print('First: {}, Second: {}, Third: {}'.format(1,2,3))
First: 1, Second: 2, Third: 3
>>> print('First: {0[0]}, Second: {0[1]}, Third: {0[2]}'.format(tup))
First: 1, Second: 2, Third: 3
%
操作符还可以用来验证参数的类型,使用不同的格式代码(比如%s
、%d
、%i
),而.format()
只支持两个转换标志:'!s'
和'!r'
。
63
这个 %
的写法已经过时了。现在推荐使用 str.format
,因为它更简单,也更容易理解:
t = 1,2,3
print('this is a tuple: {0}.'.format(t))
223
>>> thetuple = (1, 2, 3)
>>> print("this is a tuple: %s" % (thetuple,))
this is a tuple: (1, 2, 3)
这里的关键是创建一个单一的元组,也就是把你感兴趣的那个元组放在里面,像这样 (thetuple,)
。