Python编辑中的错误 TypeError: unsupported operand type(s) for +: ‘int‘ and ‘str‘

TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’ 本想把数列中1~9的序列打印出来,因为1、2、3这三个数比较特殊要打1st、2nd、3rd,所有就想着用“+”连接符号。 代码: # 序数 countst = [1,2,3,4,5,6,7,8,9] for nums in countst : if nums == ...

TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

本想把数列中1~9的序列打印出来,因为1、2、3这三个数比较特殊要打1st、2nd、3rd,所有就想着用“+”连接符号。
代码:

 # 序数
countst = [1,2,3,4,5,6,7,8,9]
for nums in countst :
    if nums == 1:
        print(nums + 'st')
    elif nums == 2:
        print(nums + 'nd' )
    elif nums == 3:
        print(nums + 'rd' )
    else:
        print(nums + 'th' )

打印的结果为:

Traceback (most recent call last):
File "E:/PyCharm/HomeStudy/venv/Include/study511.py", line 5, in <module>
 print(nums + 'st')
TypeError: unsupported operand type(s) for +: 'int' and 'str'

这是一个类型错误,意思是说Python无法识别你使用的信息,Python发现你使用了一个int类型的变量要与str类型的相关联,“+”这个符号有相加的作用也有连接的作用,然后Python就不知道如何去处理了。因此,可调用***str()函数***,它让Python将非字符串值表示为字符串。
更改后:

# 序数
countst = [1,2,3,4,5,6,7,8,9]
for nums in countst :
    if nums == 1:
     print(str(nums) + 'st')
 elif nums == 2:
     print(str(nums) + 'nd' )
 elif nums == 3:
     print(str(nums) + 'rd' )
 else:
     print(str(nums) + 'th' )

猜你喜欢

转载自blog.csdn.net/unbelievevc/article/details/132487606