Python에서 정수를 문자열로 변환
정수를 문자열로 변환하려면 어떻게 해야 하나요?
42 ⟶ "42"
그 반대의 경우는, 문자열을 float 또는 int 에 해석하는 방법을 참조해 주세요. float
는 동일하게 처리할 수 있지만 부동소수점 값이 정확하지 않기 때문에 소수점 처리가 까다로울 수 있습니다.자세한 내용은 반올림하지 않고 플로트를 문자열로 변환을 참조하십시오.
>>> str(42)
'42'
>>> int('42')
42
매뉴얼 링크:
str(x)
임의의 오브젝트를 변환하다x
현악기를 부르다x.__str__()
.
이것을 시험해 보세요.
str(i)
Python에는 타입캐스트도 타입 강제도 없습니다.변수를 명시적으로 변환해야 합니다.
개체를 문자열로 변환하려면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-string의 새로운 기능을 사용하여 문자열로 변환할 수 있으며 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로 변환
Python = > 3.6에서는f
포맷:
>>> int_value = 10
>>> f'{int_value}'
'10'
>>>
내 생각에 가장 점잖은 방법은 "이다.
i = 32 --> `i` == '32'
사용할 수 있습니다.%s
또는.format
:
>>> "%s" % 10
'10'
>>>
또는 다음 중 하나를 선택합니다.
>>> '{}'.format(10)
'10'
>>>
int 를 특정 자리수의 문자열로 변환하는 경우는, 다음의 방법을 추천합니다.
month = "{0:04d}".format(localtime[1])
상세한 것에 대하여는, 「스택 오버플로우」의 질문 「선행 0이 있는 번호의 표시」를 참조해 주세요.
Python 3.6에서 f-string을 도입하면 다음과 같이 동작합니다.
f'{10}' == '10'
실제로 전화하는 것보다 빠르다.str()
, 가독성을 희생합니다.
사실, 그것은 보다 빠르다.%x
문자열 포맷 및.format()
!
python에서 정수를 문자열로 변환하는 방법은 여러 가지가 있습니다.[ str ( integer here ) ]함수, f-string [ f ' { integer here } 、 . format() 함수 [ { } ]format ( integer here )및 '%s'% 키워드 [ integer here ]를 사용할 수 있습니다.이 메서드는 모두 정수를 문자열로 변환할 수 있습니다.
아래의 예를 참조해 주세요.
#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'>)
보다 심플한 솔루션은 다음과 같습니다.
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]
언급URL : https://stackoverflow.com/questions/961632/convert-integer-to-string-in-python
'itsource' 카테고리의 다른 글
콜과 신청의 차이점은 무엇입니까? (0) | 2022.10.26 |
---|---|
'/var/run/mysqld/mysqld 소켓을 통해 로컬 MySQL 서버에 연결할 수 없습니다.sock'(111 "Connection rejected"), (0) | 2022.10.26 |
두 텍스트 문서 간의 유사성을 계산하는 방법은 무엇입니까? (0) | 2022.10.26 |
재귀적 콜라츠 추측 함수 프로그램이 출력을 제공하지 않습니다. (0) | 2022.10.26 |
Python 로케일 오류: 지원되지 않는 로케일 설정 (0) | 2022.10.26 |