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

Python 유형 변환 및 유형 캐스팅

Python 유형 변환 및 유형 캐스팅

이 기사에서는 유형 변환과 유형 변환의 사용에 대해 알아봅니다.

Python에서 유형 변환을 배우기 전에 Python 데이터 유형에 대한 지식이 있어야 합니다.

<시간>

유형 변환

하나의 데이터 유형(정수, 문자열, 부동 소수점 등)의 값을 다른 데이터 유형으로 변환하는 프로세스를 유형 변환이라고 합니다. 파이썬에는 두 가지 유형 변환이 있습니다.

  1. 암시적 유형 변환
  2. 명시적 유형 변환
<시간>

암시적 유형 변환

암시적 유형 변환에서 Python은 자동으로 한 데이터 유형을 다른 데이터 유형으로 변환합니다. 이 프로세스는 사용자 개입이 필요하지 않습니다.

Python에서 데이터 손실을 방지하기 위해 낮은 데이터 형식(정수)을 높은 데이터 형식(float)으로 변환하는 예를 살펴보겠습니다.

예제 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'>

위의 프로그램에서

<시간>

이제 문자열과 정수를 추가하고 Python이 이를 어떻게 처리하는지 살펴보겠습니다.

예시 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() 등을 사용하여 명시적 유형 변환을 수행합니다.

이러한 유형의 변환은 사용자가 개체의 데이터 유형을 캐스트(변경)하기 때문에 유형 캐스팅이라고도 합니다.

구문:

<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. 암시적 유형 변환은 Python 인터프리터에 의해 자동으로 수행됩니다.
  3. Python은 암시적 유형 변환에서 데이터 손실을 방지합니다.
  4. 명시적 유형 변환은 유형 캐스팅이라고도 하며, 사용자가 미리 정의한 함수를 사용하여 객체의 데이터 유형을 변환합니다.
  5. 유형 캐스팅에서 특정 데이터 유형에 개체를 적용할 때 데이터 손실이 발생할 수 있습니다.

python

  1. C# 유형 변환
  2. 파이썬 키워드와 식별자
  3. Python 문, 들여쓰기 및 주석
  4. Python 변수, 상수 및 리터럴
  5. 파이썬 데이터 유형
  6. 파이썬 입력, 출력 및 가져오기
  7. Python 전역, 지역 및 비지역 변수
  8. 파이썬 숫자, 유형 변환 및 수학
  9. Python 디렉토리 및 파일 관리
  10. Python 오류 및 내장 예외