웹사이트 검색

Python에서 문자열과 Int를 연결하는 방법


소개

Python은 + 연산자를 사용하여 문자열 연결을 지원합니다. 대부분의 다른 프로그래밍 언어에서 문자열을 정수(또는 다른 기본 데이터 유형)와 연결하면 언어에서 이를 문자열로 변환한 다음 연결합니다.

그러나 Python에서 + 연산자를 사용하여 문자열을 정수와 연결하려고 하면 런타임 오류가 발생합니다.

+ 연산자를 사용하여 문자열(str)과 정수(int)를 연결하는 예를 살펴보겠습니다.

current_year_message = 'Year is '

current_year = 2018

print(current_year_message + current_year)

원하는 출력은 Year is 2018 문자열입니다. 그러나 이 코드를 실행하면 다음과 같은 런타임 오류가 발생합니다.

Traceback (most recent call last):
  File "/Users/sammy/Documents/github/journaldev/Python-3/basic_examples/strings/string_concat_int.py", line 5, in <module>
    print(current_year_message + current_year)
TypeError: can only concatenate str (not "int") to str

그렇다면 Python에서 strint를 어떻게 연결합니까? 이 작업을 수행하는 다양한 다른 방법이 있습니다.

전제 조건

이 자습서를 완료하려면 다음이 필요합니다.

  • Python 3 설치에 익숙함. Python 코딩에 익숙함. Python용 VS 코드.

이 튜토리얼은 Python 3.9.6에서 테스트되었습니다.

str() 함수 사용

intstr() 함수에 전달하면 str로 변환됩니다.

print(current_year_message + str(current_year))

current_year 정수는 문자열로 반환됩니다: Year is 2018.

% 보간 연산자 사용

printf 스타일의 문자열 형식을 사용하여 변환 사양에 값을 전달할 수 있습니다.

print("%s%s" % (current_year_message, current_year))

current_year 정수는 문자열로 보간됩니다: Year is 2018.

str.format() 함수 사용

문자열과 정수를 연결하기 위해 str.format() 함수를 사용할 수도 있습니다.

print("{}{}".format(current_year_message, current_year))

current_year 정수는 Year is 2018 문자열로 강제 변환된 유형입니다.

f-스트링 사용

Python 3.6 이상 버전을 사용하는 경우 f-문자열도 사용할 수 있습니다.

print(f'{current_year_message}{current_year}')

current_year 정수는 문자열로 보간됩니다: Year is 2018.

결론

GitHub 리포지토리에서 전체 Python 스크립트와 더 많은 Python 예제를 확인할 수 있습니다.