我很确定前三行是正确的,但我把它们包括在内,所以代码是可以理解的。
print('a is going to be a tuple:\n')
a=(1,2,3) # tuple name: a
print('%d %d %d\n' % a) # Till here everything is correct, next I'm not sure
print('b is going to be a tuple as well:\n')
b=(4,5,'cow','says','moo')
print('%d %d %s %s %s \n' % (b[0],b[1],b[2],b[3],b[4]))
print('b will be a part of a\n')
a=(1,2,3,b)
print(a)
print('The whole set of characters is %d %d %d %d %d %s %s %s') % (a[0],a[1],a[2],a[3][0],a[3][1],a[3][2],a[3][3],a[3][4])
当我运行它(在终端中)时,我收到此输出,包括错误消息:
a is going to be a tuple:
1 2 3
b is going to be a tuple as well:
4 5 cow says moo
b will be a part of a
(1, 2, 3, (4, 5, 'cow', 'says', 'moo'))
The whole set of characters is %d %d %d %d %d %s %s %s
Traceback (most recent call last):
File "tuples.py", line 10, in <module>
print('The whole set of characters is %d %d %d %d %d %s %s %s') % (a[0],a[1],a[2],a[3][0],a[3][1],a[3][2],a[3][3],a[3][4])
TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'
我不明白错误信息。它试图说什么?我也无法在代码中看到我的错误。
谢谢大家。
答案 0 :(得分:3)
在Python中,用于格式化旧字符串的%
运算符是一个中缀运算符,它不能跨函数调用语法工作。
例如,
foo = "The string is %s, the number is %d" % ("doo", 5)
在您的代码中,您需要在括号内包含运算符。
print('The whole set of characters is %d %d %d %d %d %s %s %s' % (a[0],a[1],a[2],a[3][0],a[3][1],a[3][2],a[3][3],a[3][4]))
由于您使用的是python 3,并且格式字符串中包含大量字段,因此使用format()
字符串方法可能更有效。您可以在此处将字段作为名称或索引括起来,例如:
>>> "The count is {count}, the list is {lst}".format(count=5, lst=[1, 2])
'The count is 5, the list is [1, 2]'