Programming Language/Python

[Python]Data Casting

Sergemeow 2023. 2. 18. 16:49

파이썬에서는 데이터타입의 형변환도 비교적 간단하게 이루어진다.

암시적 형변환(implicit casting)

사용자가 의도하지 않고 파이썬 내부적으로 자료형을 변환하는 경우이다.

(True + 3) #true가 1로 형변환된다. Boolean -> Integer
(3 + 5.0) #3이 3.0으로 형변환돤다. Integer -> Float

뒤 두번째 사례의 경우 반대는 성립되지 않는다.

명시적 형변환(explicit casting)

사용자가 직접 지정해주는 변환이다. 특정 함수를 이용해줘야한다.

a = '123' # a is a string
b = int(a) # casting into an integer
c = float(a) # casting into a float
d = 123 # d is an integer
e = str(d) # casting into a string

조금 메인줄기에서 벗어난 얘기지만, string을 띄어쓰기 기준으로 잘라내어 리스트를 생성하는 방법도 있다.

str_nums = '1 2 3 4 5'
listStr = str_nums.split()
map(int, sequence) #문자열의 모든 자릿수를 int로 cast
#e.g.
sum(list(map(int, str_num))) #문자열 모든자리의 합

String 형변환

str1 = 'hello' #아래 세가지 변환가능
aList = list(str1) #대괄호
bList = tuple(str1) #소괄호
cList = set(str1) #중괄호

List 형변환

list1 = [1,2,3,1,1] #아래 두가지 변환가능
aTuple = tuple(list1)
bSet = set(list1)
cStr = ''.join(list1)

Range 형변환

range1 = range(5) #아래 세가지 변환가능
aList = list(range1)
aTuple = tuple(range1)
aSet = set(range1)

Set 형변환

set1 = {1,2,3,4,5,6} #아래 두가지 변환가능
aList = list(set1)
bTuple = tuple(set1)

Dictionary 형변환

dict1 = {'key1':'value','key2':'value2'} #아래 세가지 변환가능
aList = list(dict1)
bTuple = tuple(dict1)
cSet = set(dict1)
#key 값들만 담기게 된다.