如何修复 TypeError: can only concatenate str (not list) to str?

时间:2021-04-26 19:49:24

标签: python

nums = (1,2,3,4,5,6,7,8,9)

firstNum = int(input("What's the first number of your list?"))

lastNum = int(input("What is your last number of your list?"))

odds = []
evens = []

for num in range(firstNum, lastNum):
   if num % 2 == 0:
     evens.append(num)
   
else:
   odds.append(num)
  
print("Numbers of evens:" + evens)
print("Number of odds:" + odds)

我正在尝试过滤元组中的偶数和赔率,但出现错误,我不知道如何解决

2 个答案:

答案 0 :(得分:0)

改为这样做:

gradle.properties

像这样,您不会添加字符串 (print("Numbers of evens:", evens) print("Number of odds:", odds) ) 和列表 ("Numbers of evens:")。

完整代码:

evens

输出:

firstNum = 1#int(input("What's the first number of your list?"))
lastNum = 9#int(input("What is your last number of your list?"))

odds = []
evens = []

for num in range(firstNum, lastNum):
    if num % 2 == 0:
        evens.append(num)
       
    else:
        odds.append(num)
  
print("Numbers of evens:", evens)
print("Number of odds:", odds)

答案 1 :(得分:0)

当您运行 print("Number of evens:" + evens) 时,您试图将一个字符串与一个列表连接起来,这是不可能的。相反,您应该使用 str(evens) 将偶数转换为字符串,或者使用 print() 用逗号分隔而不是串联