산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> python

파이썬 타입 변환 & 캐스팅 마스터하기: 종합 가이드

파이썬 타입 변환과 타입 캐스팅

이 글에서는 타입 변환의 개념과 타입 변환의 용도에 대해 배웁니다.

파이썬 타입 변환을 배우기 전에 파이썬 데이터 타입에 대한 지식이 있어야 합니다.


타입 변환

한 데이터 타입(정수, 문자열, 실수 등)의 값을 다른 데이터 타입으로 변환하는 과정을 타입 변환이라고 합니다. 파이썬에는 두 가지 타입 변환이 있습니다.

  1. 암시적 타입 변환(Implicit Type Conversion)
  2. 명시적 타입 변환(Explicit Type Conversion)

암시적 타입 변환

암시적 타입 변환에서 파이썬은 자동으로 한 데이터 타입을 다른 데이터 타입으로 변환합니다. 이 과정은 사용자 개입이 필요 없습니다.

데이터 손실을 피하기 위해 파이썬이 낮은 데이터 타입(정수)을 높은 데이터 타입(실수)으로 승격시키는 예제를 봅시다.

예제 1: 정수를 실수로 변환

num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("datatype of num_int:", type(num_int))
print("datatype of num_flo:", type(num_flo))
print("Value of num_new:", num_new)
print("datatype of num_new:", type(num_new))

프로그램을 실행하면 출력은 다음과 같습니다:

datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>
Value of num_new: 124.23
datatype of num_new: <class 'float'>

위 프로그램에서,


이제 문자열과 정수를 더해보고 파이썬이 어떻게 처리하는지 봅시다.

예제 2: 문자열(높은 타입)과 정수(낮은 타입) 덧셈

num_int = 123
num_str = "456"
print("Data type of num_int:", type(num_int))
print("Data type of num_str:", type(num_str))
print(num_int + num_str)

프로그램을 실행하면 출력은 다음과 같습니다:

Data type of num_int: <class 'int'>
Data type of num_str: <class 'str'>
Traceback (most recent call last):
File "python", line 7, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

위 프로그램에서,


명시적 타입 변환

명시적 타입 변환에서는 사용자가 객체의 데이터 타입을 원하는 타입으로 변환합니다. int(), float(), str() 같은 내장 함수를 사용해 명시적 타입 변환을 수행합니다.

이 변환을 타입 캐스팅(Type Casting)이라고도 하는데, 사용자가 객체의 데이터 타입을 캐스팅(변경)하기 때문입니다.

문법:

<required_datatype>(expression)

표현식에 원하는 데이터 타입 함수를 할당해 타입 캐스팅을 수행합니다.


예제 3: 명시적 변환으로 문자열과 정수 더하기

num_int = 123
num_str = "456"
print("Data type of num_int:", type(num_int))
print("Data type of num_str before Type Casting:", type(num_str))
num_str = int(num_str)
print("Data type of num_str after Type Casting:", type(num_str))
num_sum = num_int + num_str
print("Sum of num_int and num_str:", num_sum)
print("Data type of the sum:", type(num_sum))

프로그램을 실행하면 출력은 다음과 같습니다:

Data type of num_int: <class 'int'>
Data type of num_str before Type Casting: <class 'str'>
Data type of num_str after Type Casting: <class 'int'>
Sum of num_int and num_str: 579
Data type of the sum: <class 'int'>

위 프로그램에서,


기억할 핵심 포인트

  1. 타입 변환은 객체를 한 데이터 타입에서 다른 데이터 타입으로 변환하는 것.
  2. 암시적 타입 변환은 파이썬 인터프리터가 자동 수행.
  3. 파이썬은 암시적 타입 변환에서 데이터 손실을 방지함.
  4. 명시적 타입 변환은 타입 캐스팅이라고도 하며, 사용자가 내장 함수로 객체 데이터 타입을 변환.
  5. 타입 캐스팅에서는 객체를 특정 데이터 타입으로 강제하므로 데이터 손실이 발생할 수 있음.

python

  1. C# 타입 변환 마스터하기: 암시적, 명시적, Parse, Convert 메서드
  2. 파이썬 키워드와 식별자: 예약어와 명명 규칙 마스터하기
  3. 파이썬 문장, 들여쓰기, 주석: 명확한 가이드
  4. 파이썬 변수, 상수, 리터럴 – 종합 가이드
  5. 파이썬 데이터 타입 마스터하기: 실전 가이드
  6. 파이썬 입출력과 모듈 임포트 마스터하기: 실전 가이드
  7. 파이썬 전역, 지역, 비지역 변수 이해하기
  8. Python 숫자, 형 변환, 수학 마스터하기
  9. Python 디렉터리 및 파일 관리 마스터하기
  10. Python 에러와 내장 예외 마스터하기