파이썬에서 정수를 문자열로 변환하고 싶습니다. 나는 그것을 헛되이 타이핑하고 있습니다.
d = 15 d.str()
문자열로 변환하려고 하면 int
str
이라는 속성이 없는 것과 같은 오류가 표시됩니다.
질문자 :Hick
파이썬에서 정수를 문자열로 변환하고 싶습니다. 나는 그것을 헛되이 타이핑하고 있습니다.
d = 15 d.str()
문자열로 변환하려고 하면 int
str
이라는 속성이 없는 것과 같은 오류가 표시됩니다.
이 시도:
str(i)
Python에는 typecast도 없고 type coercion도 없습니다. 명시적인 방식으로 변수를 변환해야 합니다.
문자열의 객체를 변환하려면 str()
함수를 사용합니다. __str__()
이라는 메서드가 정의된 모든 객체와 함께 작동합니다. 사실로
str(a)
와 동등하다
a.__str__()
int, float 등으로 변환하려는 경우에도 동일합니다.
정수가 아닌 입력을 관리하려면:
number = raw_input() try: value = int(number) except ValueError: value = 0
>>> i = 5 >>> print "Hello, world the number is " + i TypeError: must be str, not int >>> s = str(i) >>> print "Hello, world the number is " + s Hello, world the number is 5
Python => 3.6에서는 f
형식을 사용할 수 있습니다.
>>> int_value = 10 >>> f'{int_value}' '10' >>>
Python 3.6의 경우 f-strings의 새로운 기능을 사용하여 문자열로 변환할 수 있으며 str() 함수에 비해 더 빠릅니다. 다음과 같이 사용됩니다.
age = 45 strAge = f'{age}'
이러한 이유로 Python은 str() 함수를 제공합니다.
digit = 10 print(type(digit)) # Will show <class 'int'> convertedDigit = str(digit) print(type(convertedDigit)) # Will show <class 'str'>
더 자세한 답변은 Python Int를 String으로, Python String을 Int로 변환 문서를 참조하세요.
내 생각에 가장 적절한 방법은 ``입니다.
i = 32 --> `i` == '32'
%s
또는 .format
사용할 수 있습니다.
>>> "%s" % 10 '10' >>>
또는:
>>> '{}'.format(10) '10' >>>
int를 특정 자리의 string형으로 변환하고 싶은 분은 아래 방법을 추천합니다.
month = "{0:04d}".format(localtime[1])
자세한 내용은 스택 오버플로 질문 표시 번호 선행 0을 참조하세요.
Python 3.6에 f-문자열 이 도입되면서 다음과 같이 작동합니다.
f'{10}' == '10'
가독성을 희생 str()
호출하는 것보다 빠릅니다.
사실, %x
문자열 형식화 및 .format()
보다 빠릅니다!
다음은 더 간단한 솔루션입니다.
one = "1" print(int(one))
>>> 1
위의 프로그램에서 int() 는 정수의 문자열 표현을 변환하는 데 사용됩니다.
참고: 문자열 형식의 변수는 변수가 완전히 숫자로 구성된 경우에만 정수로 변환할 수 있습니다.
같은 방식으로 str() 은 정수를 문자열로 변환하는 데 사용됩니다.
number = 123567 a = [] a.append(str(number)) print(a)
변수(a)가 문자열임을 강조하기 위해 목록을 사용하여 출력을 인쇄했습니다.
>>> ["123567"]
그러나 목록이 문자열과 정수를 저장하는 방식의 차이점을 이해하려면 아래 코드를 먼저 보고 출력을 보십시오.
a = "This is a string and next is an integer" listone=[a, 23] print(listone)
>>> ["This is a string and next is an integer", 23]
파이썬에서 정수를 문자열로 변환하는 방법에는 여러 가지가 있습니다. [ str(integer here) ] 함수, f-string [ f'{integer here}'], .format()function [ '{}'.format(integer here) 및 심지어 '%s' % 키워드 [ '%s'% 정수]. 이 모든 방법은 정수를 문자열로 변환할 수 있습니다.
아래 예를 참조하십시오
#Examples of converting an intger to string #Using the str() function number = 1 convert_to_string = str(number) print(type(convert_to_string)) # output (<class 'str'>) #Using the f-string number = 1 convert_to_string = f'{number}' print(type(convert_to_string)) # output (<class 'str'>) #Using the {}'.format() function number = 1 convert_to_string = '{}'.format(number) print(type(convert_to_string)) # output (<class 'str'>) #Using the '% s '% keyword number = 1 convert_to_string = '% s '% number print(type(convert_to_string)) # output (<class 'str'>)
단항 숫자 체계 가 필요한 경우 다음과 같이 정수를 변환할 수 있습니다.
>> n = 6 >> '1' * n '111111'
음수 정수 지원이 필요한 경우 다음과 같이 작성할 수 있습니다.
>> n = -6 >> '1' * n if n >= 0 else '-' + '1' * (-n) '-111111'
0은 이 경우 빈 문자열을 사용하는 특수한 경우이며, 맞습니다.
>> n = 0 >> '1' * n if n >= 0 else '-' + '1' * (-n) ''
출처 : http:www.stackoverflow.com/questions/961632/converting-integer-to-string-in-python
git 저장소에서 디렉토리를 제거하는 방법은 무엇입니까? (0) | 2022.03.04 |
---|---|
JSON 파일을 예쁘게 인쇄하는 방법은 무엇입니까? (0) | 2022.03.04 |
Python에서 문자열 반전 (0) | 2022.03.04 |
Android 애플리케이션에서 활동 간에 데이터를 어떻게 전달합니까? (0) | 2022.03.04 |
객체 배열에서 속성 값을 배열로 추출 (0) | 2022.02.27 |