한양과학기술고등학교

에듀테크 프로젝트 대시보드

형변환 (캐스팅)

int() str() repr() list() TypeError

파이썬은 대부분 명시적 변환을 요구합니다. 숫자끼리만 암시적으로 섞입니다.

1. 변환 함수

함수예시결과
int(x)int("42"), int(3.9)42, 3 (절삭)
float(x)float("3.14")3.14
str(x)str(42)'42'
bool(x)bool(0), bool("a")False, True
list(x)list("abc")['a','b','c']
tuple(x), set(x)set([1,1,2]){1, 2}
dict(x)dict([("a",1)]){'a': 1}

2. int() 자세히

int("42")          # => 42
int("  42  ")      # => 42   (공백 허용)
int("0xFF", 16)    # => 255  (진법 지정)
int("101", 2)      # => 5
int(3.99)          # => 3    (내림이 아니라 0 방향 절삭)
int(-3.99)         # => -3

# int("3.14")       # ValueError — 소수점 문자열은 float 거쳐야
int(float("3.14")) # => 3

3. str() vs repr()

import datetime
d = datetime.date(2024, 1, 15)
str(d)    # => '2024-01-15'          (사람용)
repr(d)   # => 'datetime.date(2024, 1, 15)'  (개발자용, 재현 가능)

str("hi")   # => 'hi'
repr("hi")  # => "'hi'"   (따옴표 포함)

# f-string 에서 !r 로 repr 선택
f"{d!r}"  

4. 컬렉션 간 변환

list((1, 2, 3))        # => [1, 2, 3]
tuple([1, 2, 3])       # => (1, 2, 3)
set([1, 2, 2, 3])      # => {1, 2, 3}   (중복 제거)
sorted({3, 1, 2})      # => [1, 2, 3]

d = {"a": 1, "b": 2}
list(d)                # => ['a', 'b']       (키)
list(d.values())       # => [1, 2]
list(d.items())        # => [('a', 1), ('b', 2)]
dict([("x", 1), ("y", 2)])   # => {'x': 1, 'y': 2}

5. 암시적 변환과 그 한계

3 + 4.0        # => 7.0   (int → float 승격)
True + 1       # => 2

"나이: " + 17         # TypeError: can only concatenate str
"나이: " + str(17)    # => '나이: 17'
f"나이: {17}"         # 더 간단

6. 안전한 변환

def to_int(s, default=0):
    try:
        return int(s)
    except (ValueError, TypeError):
        return default

to_int("42")     # => 42
to_int("abc")    # => 0
to_int(None)     # => 0

# "-5".isdigit() 은 False — 부호/소수점은 못 거른다
"명시적인 것이 암시적인 것보다 낫다 (Explicit is better than implicit)"