파이썬 TypeError: can only concatenate str
TypeError: can only concatenate str (not "int") to str
문자열 + 수를 하려 할 때 나는 오류예요. +는 문자열끼리는 이어 붙이고 수끼리는 더하는데, 둘이 섞이면 어느 쪽을 하라는 건지 알 수 없어서 멈춰요. 괄호 안의 not "int"는 문자열 뒤에 붙이려던 것이 정수였다는 뜻이에요. 오류가 난 줄의 + 양쪽이 무엇인지 보면 돼요.
원인 1. 글자와 수를 + 로 이어 찍으려 했어요
다른 언어에서는 되는 곳도 있지만, 파이썬은 수를 알아서 문자열로 바꿔 주지 않아요.
틀린 코드
age = 12print("age: " + age)Traceback (most recent call last): File "main.py", line 2, in <module> TypeError: can only concatenate str (not "int") to str
고친 코드
가장 쉬운 방법은 f-string이에요. print에 쉼표로 나눠 줘도 되고(사이에 빈칸이 하나 들어가요), str()로 수를 문자열로 바꿔서 붙여도 돼요.
age = 12print(f"age: {age}")print("age:", age)print("age: " + str(age))age: 12 age: 12 age: 12
원인 2. input()으로 받은 값에 수를 더했어요
input()이 돌려주는 것은 늘 문자열이에요. 5를 입력해도 "5"예요. 여기에 1을 더하면 문자열 + 수가 돼요.
틀린 코드
n = input()print(n + 1)5
Traceback (most recent call last): File "main.py", line 2, in <module> TypeError: can only concatenate str (not "int") to str
고친 코드
계산할 값은 받자마자 int()로 바꾸세요. 소수라면 float()예요.
원인 3. 반복문에서 문자열에 수를 이어 붙였어요
빈 문자열 ""로 시작한 변수에 수를 += 하면 같은 오류가 나요.
틀린 코드
s = ""for i in range(1, 4): s += iprint(s)Traceback (most recent call last): File "main.py", line 3, in <module> TypeError: can only concatenate str (not "int") to str
고친 코드
붙일 때마다 str(i)로 바꾸세요. 사이에 글자를 끼워 이으려면 join이 편해요.
s = ""for i in range(1, 4): s += str(i)print(s)print("-".join(str(i) for i in range(1, 4)))123 1-2-3
이 오류가 났을 때 확인할 것
- 오류 글의
line뒤 수가 오류가 난 줄이에요. 그 줄의+왼쪽과 오른쪽이 각각 문자열인지 수인지 보세요. - 모르겠으면 그 줄 위에
print(type(x))를 넣어 보세요.<class 'str'>이면 문자열,<class 'int'>이면 정수예요. - 이어 붙이려던 거라면 수 쪽을
str()로 감싸거나 f-string을 쓰세요. - 더하려던 거라면 문자열 쪽을
int()나float()로 바꾸세요.input()으로 받은 값인지 확인하세요. - 순서가 반대(수 + 문자열)이면 오류 글이
unsupported operand type(s) for +: 'int' and 'str'로 달라져요. 원인은 같아요.