Python의 Casting (타입 변환)#
Python에서 “형 변환"은 데이터 유형을 다른 데이터 유형으로 변환하는 것을 의미합니다.
Python은 동적 타입 언어이기 때문에 변수의 데이터 유형을 명시적으로 변환하는 것이 필요할 때가 있습니다.
1. int -> float#
다음 코드에서 변수 a 는 int type 입니다.b=float(a) 처럼 변수 a를 float type으로 casting 했기 때문에, b는 float type 이며 값은 실수 10.0 입니다.
a = 10
b = float(a)2. float -> int#
다음 코드는 float type c를 int type으로 Casting하여 변수 d에 저장하는 코드 입니다.d는 int type이며 값은 정수 20 입니다.
c = 20.0
d = int(c)3. float -> int#
float type에서 int type으로 변환 될 때, 소수점은 버림 처리 됩니다. (truncation)
따라서, 변수 f 의 값은 정수 30 입니다.
e = 30.8
f = int(e)4. int/float -> string#
다음 코드는 int/float type을 string type으로 변환하는 예제 입니다.
변수 h 는 string type이며 값은 ‘40’ 입니다.
g = 40
h = str(g)5. string -> int/float#
다음 코드는 string type을 int/float type으로 변환하는 예제 입니다.
변수 j 는 int type이며 값은 50 입니다.
변수 k 는 float type이며 값은 50.0 입니다.
i = '50'
j = int(i)
k = float(i)