이 글에서는 파이썬의 다양한 데이터 유형(자료형)과 변수 간 형 변환 방법을 예제 코드와 함께 살펴봅니다.
파이썬 데이터 유형
파이썬에서 변수를 선언하면 해당 변수는 다양한 데이터 유형의 값을 가질 수 있습니다. 별도의 타입 선언 없이 값을 할당하기만 하면 파이썬이 자동으로 자료형을 판단합니다.
파이썬이 기본으로 제공하는 내장 데이터 유형은 다음과 같습니다.
- str – 문자열
- int, float, complex – 숫자형
- list, tuple – 시퀀스형
- dict – 매핑형(딕셔너리)
- set – 집합형
- bool – 불리언(참/거짓)
- bytes, bytearray – 바이너리형
텍스트 유형: str
str은 문자열(string) 변수를 선언할 때 사용하는 데이터 유형입니다.
x = "some string"
y = str("another string")
숫자 유형: int, float, complex
숫자 변수를 만들 때는 int(정수), float(실수), complex(복소수)를 사용합니다.
# int
a = 5
b = int(5)
# float
c = 5.5
d = float(5.5)
# complex
e = 1j
f = complex(1j)
시퀀스 유형: list, tuple
시퀀스 유형의 변수를 만들 때는 list 또는 tuple을 사용합니다.
list: 순서가 있고 변경 가능(mutable)한 컬렉션입니다. 중복 요소를 허용합니다.tuple: 순서가 있지만 변경 불가능(immutable)한 컬렉션입니다. 중복 요소를 허용합니다.
# list
colors = ['red', 'green', 'blue']
colors_list = list(('red', 'green', 'blue'))
# tuple
fruits = ('apple', 'orange', 'banana')
fruits_tuple = tuple(('apple', 'orange', 'banana'))
매핑 유형: dict
맵(map) 또는 딕셔너리(dictionary)를 만들 때는 dict를 사용합니다.
딕셔너리는 키(key)와 값(value)의 쌍으로 데이터를 저장하는 컬렉션으로, 변경 가능하며 인덱싱을 지원합니다.
people = {"name": "John", "age": 45}
people_dict = dict(name="John", age=45)
집합 유형: set
set은 순서가 없고 인덱싱을 지원하지 않는 컬렉션입니다. 집합을 만들 때는 set을 사용합니다.
status_codes = {"200", "300", "400", "500"}
status_codes = set(("200", "300", "400", "500"))
불리언 유형: bool
bool 키워드를 사용하면 참(True) 또는 거짓(False) 값을 가지는 변수를 만들 수 있습니다.
is_valid = False
valid = bool(is_valid)
바이너리 유형: bytes, bytearray
바이너리 데이터 유형은 다음과 같이 생성할 수 있습니다.
# bytes
a = b"some_text"
b = bytes(5)
# bytearray
c = bytearray(3)
변수의 자료형 확인 방법
변수의 자료형을 확인하려면 type() 함수 안에 해당 변수를 넣으면 됩니다.
colors_list = list(('red', 'green', 'blue'))
print(type(colors_list))
print(colors_list)
fruits_tuple = tuple(('apple', 'orange', 'banana'))
print(type(fruits_tuple))
print(fruits_tuple)
출력 결과:
<class 'list'>
['red', 'green', 'blue']
<class 'tuple'>
('apple', 'orange', 'banana')
파이썬 데이터 유형 변환
파이썬은 한 데이터 유형을 다른 유형으로 직접 변환할 수 있는 형 변환 함수들을 제공하며, 실무에서 매우 유용하게 활용됩니다. 아래는 대표적인 변환 예제입니다.
int → float 변환
x = 5
y = float(x)
print(y)
출력 결과:
5.0
float → int 변환
x = 5.0
y = int(x)
print(y)
출력 결과:
5
문자열 → 리스트 변환
s = "devqa"
t = list(s)
print(t)
출력 결과:
['d', 'e', 'v', 'q', 'a']
문자열 → 튜플 변환
s = "devqa"
t = tuple(s)
print(t)
출력 결과:
('d', 'e', 'v', 'q', 'a')
문자열 → 집합 변환
s = "devqa"
t = set(s)
print(t)
출력 결과:
{'d', 'e', 'a', 'v', 'q'}