TypeError:不支持操作数类型


def arithmetic_arranger(problems):

if len(problems)>5:
print("Error: Too many problems.")
for cc in problems:
it=cc.split()
fi=it[0]
se=it[1]
th=it[2]
#print(fi)
### 4 digits and cant be more than 4
if len(fi)>4 or len(th)>4:
print('Error: Numbers cannot be more than four digits.')
if not fi.isnumeric() or not th.isnumeric():
print('Error: Numbers must only contain digits.')
if  se == '+' or se == '-':
print('Error: Operator must be '+' or '-'.')
#arithmetic_arranger(['1 + 22'])
arithmetic_arranger(['33 2 22','3 4 5','55 - 5'])

错误消息:

Traceback (most recent call last):
File "C:Usersnrky1Desktoppython newass1.py", line 22, in <module>
arithmetic_arranger(['33 2 22','3 4 5','55 - 5'])
File "C:Usersnrky1Desktoppython newass1.py", line 19, in arithmetic_arranger
print('Error: Operator must be '+' or '-'.')
TypeError: unsupported operand type(s) for -: 'str' and 'str'

问题:当列表中的元素是字符串时,为什么会出现此错误?当我打印时,结果是:'2','4','-'我应该如何更正代码?

您必须转义字符串中的引号。否则,python将不知道字符串是否在继续。一旦第一个内引号出现,python就会认为字符串已经结束,然后很可能会出现语法错误。

因此,在用双引号声明的字符串(如"This " is a quotation mark."(内部,需要转义像"This " is a quotation mark."这样的内引号。这同样适用于代码中的单引号:

print('Error: Operator must be '+' or '-'.')

或者,您可以用其他外引号声明字符串:

print("Error: Operator must be '+' or '-'.")

最新更新