Python แปลงข้อมูลระหว่างชนิดต่างๆ ได้ง่าย มีฟังก์ชันต่างๆ สำหรับ type conversion แปลง string เป็นตัวเลข แปลงระหว่าง container types ฯลฯ
1. String → Numeric Types
int() - แปลงเป็นจำนวนเต็ม
str_number = '56'
print(int(str_number)) # 56 (base 10 default)
print(int(str_number, 16)) # 86 (base 16 = hex)
print(int(str_number, 12)) # 66 (base 12)
float() - แปลงเป็นทศนิยม
str_number = '25.897'
print(float(str_number)) # 25.897
2. String/Char ↔ ASCII และ Base Conversion
# Char to ASCII
print('ASCII value of "G" is:', ord('G')) # 71
# Decimal to other bases
print('Hexadecimal of 254:', hex(254)) # 0xfe
print('Octal of 62:', oct(62)) # 0o76
print('Binary of 56:', bin(56)) # 0b111000
ผลลัพธ์
ASCII value of "G" is: 71
Hexadecimal value of 254 is: 0xfe
Octal value of 62 is: 0o76
Binary value of 56 is: 0b111000
3. แปลงระหว่าง Container Types
my_list = [10, 20, 30, 40, 50]
my_set = {10, 10, 20, 30, 20, 50, 20} # set ลบ duplicate เอง
print('List to tuple:', tuple(my_list)) # (10, 20, 30, 40, 50)
print('List to set:', set(my_list)) # {40, 10, 50, 20, 30}
print('Set to list:', list(my_set)) # [10, 20, 50, 30] (ลำดับไม่เกรน)
4. Complex Numbers
my_complex = complex(10, 5) # real=10, imag=5
print(my_complex) # (10+5j)
# เข้าถึงส่วนจริงและจินตภาพ
print(my_complex.real) # 10.0
print(my_complex.imag) # 5.0
5. Tuple → Dictionary
Tuple ที่มีคู่ (key, value) แปลงเป็น dict ได้ด้วย 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}
สรุปฟังก์ชันแปลงชนิดหลัก
| ฟังก์ชัน | แปลงจาก | แปลงเป็น |
|---|---|---|
int(x, base) | string/number | integer |
float(x) | string/number | float |
str(x) | any | string |
list(x) | iterable | list |
tuple(x) | iterable | tuple |
set(x) | iterable | set |
dict(x) | pairs iterable | dict |
complex(r, i) | real, imag | complex |
ord(c) | char | int (ASCII/Unicode) |
chr(i) | int | char |
hex/oct/bin | int | string (base 16/8/2) |