Python 多格式说明符中的奇怪错误

Python 多格式说明符中的奇怪错误,python,tuples,Python,Tuples,我很确定前3行是正确的,但是我包括了它们,所以代码是可以理解的 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(

我很确定前3行是正确的,但是我包括了它们,所以代码是可以理解的

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'
a将是一个元组:
1 2 3
b也是一个元组:
4.5牛说哞
b将是a的一部分
(1,2,3,(4,5,'cow','says','moo'))
整个字符集是%d%d%d%d%d%s%s
回溯(最近一次呼叫最后一次):
文件“tuples.py”,第10行,在
打印('整组字符为%d%d%d%d%d%s%s')%(a[0]、a[1]、a[2]、a[3][0]、a[3][1]、a[3][2]、a[3][3]、a[3][4])
TypeError:不支持%的操作数类型:“非类型”和“元组”
我不明白错误信息。它想说什么?我也看不到代码中的错误


谢谢大家。

在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,并且格式字符串中有大量字段,因此使用字符串方法可能更有效。在这里,您可以将字段括起来作为名称或索引,例如:

>>> "The count is {count}, the list is {lst}".format(count=5, lst=[1, 2])
'The count is 5, the list is [1, 2]'

在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,并且格式字符串中有大量字段,因此使用字符串方法可能更有效。在这里,您可以将字段括起来作为名称或索引,例如:

>>> "The count is {count}, the list is {lst}".format(count=5, lst=[1, 2])
'The count is 5, the list is [1, 2]'

您的问题是,您正在格式化的值应该在打印调用中。你把它们放在外面。使用
print('整组字符是%d%d%d%d%d%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
,它比this@ChristianDean哦,是的,谢谢,真是个新手!!没错,乔什温斯坦。这是一个很好的观点。您的问题是,您正在格式化的值应该在打印调用中。你把它们放在外面。使用
print('整组字符是%d%d%d%d%d%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
,它比this@ChristianDean哦,是的,谢谢,真是个新手!!没错,乔什温斯坦。这是一个很好的观点。也许你应该在回答中提到你关于使用
.format
的建议。也许你应该在回答中提到你关于使用
.format
的建议。