logo

Python에서 정수를 문자열로 변환

Python에서는 내장된 함수를 사용하여 정수를 문자열로 변환할 수 있습니다. str() 기능. str() 함수는 모든 것을 취합니다. str() 그렇게 하는 유일한 방법은 아닙니다. 이러한 유형의 변환은 다음을 사용하여 수행할 수도 있습니다. %에스 키워드, .체재 기능을 사용하거나 f-문자열 기능.

다음은 Python에서 정수를 문자열로 변환하는 가능한 방법 목록입니다.

1. str() 함수 사용하기



통사론: str(정수_값)

예:

파이썬3




num>=> 10> # check and print type of num variable> print>(>'Type of variable before conversion : '>,>type>(num))> # convert the num into string> converted_num>=> str>(num)> # check and print type converted_num variable> print>(>'Type After conversion : '>,>type>(converted_num))>

>

>

산출:

Type of variable before conversion : Type After conversion :>

2. %s 키워드 사용

통사론: %s % 정수

예:

파이썬3




num>=> 10> # check and print type of num variable> print>(>'Type of variable before conversion : '>,>type>(num))> # convert the num into string and print> converted_num>=> '% s'> %> num> print>(>'Type after conversion : '>,>type>(converted_num))>

>

>

산출:

Type of variable before conversion : Type after conversion :>

3. .format() 함수 사용

통사론: '{}'.format(정수)

예:

파이썬3




num>=> 10> # check and print type of num variable> print>(>'Type before conversion : '>,>type>(num))> # convert the num into string and print> converted_num>=> '{}'>.>format>(num)> print>(>'Type after conversion :'>,>type>(converted_num))>

>

>

산출:

Type before conversion : Type after conversion :>

4. f-문자열 사용

통사론: f'{정수}'

예:

파이썬3




num>=> 10> # check and print type of num variable> print>(>'Type before conversion : '>,>type>(num))> # convert the num into string> converted_num>=> f>'{num}'> # print type of converted_num> print>(>'Type after conversion : '>,>type>(converted_num))>

>

>

산출:

Type before conversion : Type after conversion :>

5. __str__() 메소드 사용

구문: 나는 정수.__str__()

파이썬3




num>=> 10> # check and print type of num variable> print>(>'Type before conversion : '>,>type>(num))> # convert the num into string> converted_num>=> num.__str__()> # print type of converted_num> print>(>'Type after conversion : '>,>type>(converted_num))>

>

>

산출:

Type before conversion : Type after conversion :>

6. str.isdigit() 사용

파이썬3


fmoviez



str_value>=> '1234'> if> str_value.isdigit():> >int_value>=> int>(str_value)> >print>(int_value)> >print>(>type>(int_value))> else>:> >raise> ValueError(>'Invalid literal for int(): {}'>.>format>(str_value))>

>

>

산출

1234>

7.join() 메소드 사용:

Join() 메소드는 정수 목록을 문자열로 변환하는 데 사용됩니다. list() 함수를 사용하여 정수를 문자 목록으로 변환한 다음 Join() 메서드를 사용하여 결합합니다.

파이썬3




num>=> 10> # check and print type of num variable> print>(>'Type before conversion : '>,>type>(num))> # convert the num into string> converted_num>=> ''.join(>list>(>str>(num)))> # print type of converted_num> print>(>'Type after conversion : '>,>type>(converted_num))>

>

>

산출

Type before conversion : Type after conversion :>

시간 복잡도: O(N) 여기서 n은 정수의 자릿수입니다.

공간 복잡도:O(N) ~처럼 n개의 요소가 있는 문자 목록을 만들어야 합니다.