English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Python을 사용하면 데이터를 다른 타입으로 쉽게 변환할 수 있습니다. 타입 변환에는 다양한 기능이 있습니다. 문자열 객체를 수치형으로 변환하거나, 다른 컨테이너 타입 간의 변환을 수행할 수 있습니다.
이 절에서는 Python을 사용하여 변환하는 방법을 알아보겠습니다。
String 유형 객체를 Numeric 객체로 변환하려면, 이int()
,float()
등 다양한 방법을 사용할 수 있습니다.int()
을 사용하여, 어떤 숫자도 문자열로 변환할 수 있습니다.10기준으로). 문자열 유형 파라미터를 사용하며, 기본 기수는10를 사용하여, 그 기수에서 십진수로 변환할 수 있습니다.
동일하게, 이float()
이 방법은 십진수 형태의 값을 포함한 문자열을 float로 변환할 수 있습니다。
str_number = '56' print(int(str_number)) # default base is 10 print(int(str_number, 16)) # From Hexadecimal print(int(str_number, 12)) # From a number where base is 12 str_number = '25.897' print(float(str_number)) # convert string to floating point value
출력 결과
56 86 66 25.897
众所周知,字符串是字符的 집합。但是在Python에서는, 문자의 ASCII 값을 직접 가져올 수 없습니다。해당ord()
方法将字符转换为其ASCII值。
还有另外一些方法,如hex()
,ord()
,bin()
转换十进制数为十六进制,八进制,二进制分别编号。
print('ASCII value of "G" is: ' + str(ord('G'))) print('Hexadecimal value of 254 is: ' + str(hex(254)) print('Octal value of 62 is: ' + str(oct(62)) print('Binary value of') 56 is: ' + str(bin(56))
출력 결과
ASCII value of "G" is: 71 Hexadecimal value of 254 is: 0xfe Octal value of 62 is: 0o76 Binary value of 56 is: 0b111000
Python에서는 목록, 튜플, 집합과 같은 다양한 컨테이너 타입 객체가 있으며, 하나의 타입의 컨테이너를 다른 타입의 컨테이너로 변환할 수 있습니다.list()
,tuple()
,set()
등.
my_list = [10, 20, 30, 40, 50] my_set = {10, 10, 20, 30, 20, 50, 20} print('From list to tuple: ' + str(tuple(my_list))) print('From list to set: ' + str(set(my_list))) print('From set to list: ' + str(list(my_set)))
출력 결과
From list to tuple: (10, 20, 30, 40, 50) From list to set: {40, 10, 50, 20, 30} From set to list: [10, 20, 50, 30]
Python에서는 복수 클래스가 있습니다. 따라서 이 메서드를 사용하여 두 정수(실수 부분과 허수 부분)를 복수로 변환할 수 있습니다.
my_complex = complex(10, 5) #convert to complex number print(my_complex)
출력 결과
(10+5j)
특징dict()
메서드를 통해 변환할 수 있습니다.
my_tuples = (('Tiger', 4), ('Cat', 6), ('Dog', 8), ('Elephant', 10)) my_dict = dict(my_tuples) print(my_dict)
출력 결과
{'Tiger': 4, 'Elephant': 10, 'Dog': 8, 'Cat': 6}