우리 모두는 데이터 유형을 선언하고 작업할 수 있습니다. 우리는 그들의 상호 전환에 대해 궁금해 한 적이 있습니까? 이 기사에서는 유형 캐스팅이라고도 불리는 Python의 내장 함수를 사용하여 이러한 데이터 유형을 변환하는 방법을 배웁니다. 유형 캐스팅에는 암시적 및 명시적의 두 가지 유형이 있습니다. 이 모듈에서는 명시적 유형 캐스팅에 대해서만 논의할 것입니다.
이제 몇 가지 기본 및 유형 변환을 살펴보겠습니다.
Python의 정수형 변환
int() 함수를 사용하면 모든 데이터 유형을 정수로 변환할 수 있습니다. Base는 정수 값이 속한 밑을 의미하는 Base 및 Number라는 두 개의 매개변수를 정확히 허용합니다(2진[2], 8진[8], 16진법[16]).
Python의 부동 소수점 유형 변환
float() 함수를 사용하면 모든 데이터 유형을 부동 소수점 숫자로 변환할 수 있습니다. 정확히 하나의 매개변수, 즉 변환해야 하는 데이터 유형의 값을 허용합니다.
예시
#Type casting
value = "0010110"
# int base 2
p = int(value,2)
print ("integer of base 2 format : ",p)
# default base
d=int(value)
print ("integer of default base format : ",d)
# float
e = float(value)
print ("corresponding float : ",e) 출력
integer of base 2 format : 22 integer of default base format : 10110 corresponding float : 10110.0
위의 코드에서는 Python에서 base를 사용하여 정수를 변환했습니다.
Python의 튜플 유형 변환
tuple() 함수를 사용하면 튜플로 변환할 수 있습니다. 문자열이나 목록 중 정확히 하나의 매개변수를 허용합니다.
Python의 목록 유형 변환
list() 함수를 사용하면 모든 데이터 유형을 목록 유형으로 변환할 수 있습니다. 정확히 하나의 매개변수를 허용합니다.
Python의 사전 유형 변환
dict() 함수는 순서의 튜플(키, 값)을 사전으로 변환하는 데 사용됩니다. 키는 본질적으로 고유해야 합니다. 그렇지 않으면 중복 값이 무시됩니다.
예시
#Type casting
str_inp = 'Tutorialspoint'
# converion to list
j = list(str_inp)
print ("string to list : ")
print (j)
# conversion to tuple
i = tuple(str_inp)
print ("string to tuple : ")
print (i)
# nested tuple
tup_inp = (('Tutorials', 0) ,('Point', 1))
# conversion to dictionary
c = dict(tup_inp)
print ("list to dictionary : ",c)
# nested list
list_inp = [['Tutorials', 0] ,['Point', 1]]
# conversion to dictionary
d = dict(list_inp)
print ("list to dictionary : ",d) 출력
string to list :
['T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't']
string to tuple :
('T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't')
list to dictionary : {'Tutorials': 0, 'Point': 1}
list to dictionary : {'Tutorials': 0, 'Point': 1} Python의 문자열 유형 변환
str() 함수는 정수 또는 부동 소수점을 문자열로 변환하는 데 사용됩니다. 정확히 하나의 인수를 허용합니다.
Python의 Ascii chr() 및 ord() 유형 변환
chr()-이 함수는 정수 유형을 문자 유형으로 변환하는 데 사용됩니다.
ord()-이 함수는 문자 유형을 정수 유형으로 변환하는 데 사용됩니다.
예시
#Type casting
char_inp = 'T'
#converting character to corresponding integer value
print ("corresponding ASCII VALUE: ",ord(char_inp))
int_inp=92
#converting integer to corresponding Ascii Equivalent
print ("corresponding ASCII EQUIVALENT: ",chr(int_inp))
#integer and float value
inp_i=231
inp_f=78.9
# string equivalent
print ("String equivalent",str(inp_i))
print ("String equivalent",str(inp_f)) 출력
corresponding ASCII VALUE: 84 corresponding ASCII EQUIVALENT: \ String equivalent 231 String equivalent 78.9
결론
이 기사에서 우리는 Python 3.x의 명시적 유형 캐스팅에 대해 배웠습니다. 또는 그 이전.