프로그래밍

(Python) TypeError: can only concatenate str (not "int") to str

성수동이민기 2020. 9. 4. 11:18

 

[정상적으로 실행되던 코드]

path = "/Users/YEO/AppData/Local/Programs/Python/Python38/2019/" + team_name[0].text + "/"

 

 

[시도하고자 했던 코드]

year = 2019

...중략

path = "/Users/YEO/AppData/Local/Programs/Python/Python38/"+ year + "/" + team_name[0].text + "/"

 

[발생한 에러]

Traceback (most recent call last):

  File "C:\Users\YEO\AppData\Local\Programs\Python\Python38\practice_crawling22_Player_name_compare_excel.py", line 54, in <module>
    path = "/Users/YEO/AppData/Local/Programs/Python/Python38/"+ year + "/" + team_name[0].text + "/"
TypeError: can only concatenate str (not "int") to str

 

 

 

[코드를 짠 의도]

year를 미리 선언하여, 연도를 바꾸어 탐색을 하더라도 year값만 바꾸어주면 되게 만들어주고 싶었다.

 

 

 

 코드를 짜고 파이썬을 돌리다가, 다음과 같은 에러가 나왔다.

 

 타입에러다, str끼리만 결합할 수 있다 뭐 이런 말 같다.

 

 다들 아시겠지만, int는 정수 변수 타입이고, str은 문자열 변수 타입이다.

 

 문자열 변수 타입끼리 더하는 와중에, 정수 변수 타입이 들어와서 에러가 난 것이다.

 

 

 

해결방법 (2019를 문자열 타입으로 선언해준다.)

1. year = '2019'

2. year = str(2019)

 

 

[잘 돌아가는 코드]

year = str(2019)

...중략

path = "/AppData/Local/Programs/Python/Python38/"+ year + "/" + team_name[0].text + "/"

 

 

제 시행착오를 일기로 남긴 글이지만, 누군가에게 도움이 된다면 좋겠습니다.