TypeError: unsupported operand type(s) for +: 'int' and 'str' I wanted to print out the sequence of 1~9 in the sequence, because the three numbers 1, 2, and 3 are special and need to be typed as 1st, 2nd, and 3rd , all thinking about using "+" to connect symbols. Code: # ordinal 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’
I wanted to print out the sequence of 1~9 in the number sequence, because the three numbers 1, 2, and 3 are special to type 1st, 2nd, and 3rd, so I thought about using "+" to connect symbols.
code:
# 序数
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' )
The printed result is:
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'
This is a type error, which means that Python cannot recognize the information you use. Python finds that you have used a variable of type int to be associated with a variable of type str. The symbol "+" has the function of addition and connection . Then Python doesn't know how to deal with it . Therefore, you can call the ***str() function***, which tells Python to represent non-string values as strings.
After change:
# 序数
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' )