파이썬 도와주세요! TypeError: unsupported operand type(s) for +: 'int' and 'str'

조회수 9075회
numbers = (1,2,3,4,5,6,7,8,9)
for list in numbers :
    if list==1 :
        print("1" + "st")
    elif list==2 :
        print("2" + "nd")
    elif list==3 :
        print("3" + "rd")
    else :
        print(list + "th")

이렇게 하면 TypeError: unsupported operand type(s) for +: 'int' and 'str' 해당 오류가 나옵니다. 결과를

1st
2nd
3rd
4th
5th
6th
7th
8th
9th 

이렇게 나오게 하고 싶은데 어떻게 해야할까요?

1 답변

  • int와 str은 +할 수 없습니다.

    +는 같은 type끼리 가능하죠.

    이 문제를 해결하기 위해, 크게 두개의 해결책이 보입니다.

    따로따로 출력을 하거나, list에 있는 값을 형변환 시키면 되죠.

    numbers = (1,2,3,4,5,6,7,8,9)
    for list in numbers :
        # print(list)
        if list==1:
            print("1", "st")
        elif list==2:
            print("2", "nd")
        elif list==3:
            print("3", "rd")
        else:
            print(list, "th")
    
    numbers = (1,2,3,4,5,6,7,8,9)
    for list in numbers :
        if list==1 :
            print("1" + "st")
        elif list==2 :
            print("2" + "nd")
        elif list==3 :
            print("3" + "rd")
        else :
            print(str(list) + "th")
    

    나머지는 상관 없지만, 마지막 else문에서 list + "th"가 불가능합니다.

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)