ฟังก์ชั่นสำหรับแปลงชนิดข้อมูล ใน ไพทอน Python Data Type Conversion
ไพทอน ถึงแม้จะเป็นภาษาที่ กำหนด ชนิดของข้อมูลให้เราเองตอนที่เราสร้าง ตัวแปร แล้วแต่บางครั้งเราอาจต้องการแปรชนิดของ ตัวแปร เพื่อนำไปใช้ ต่อ มาดู ฟังก์ชั่นที่ ไพทอน เตรียมไว้ให้เราใช้สำหรับ การแสดง ชนิดของข้อมูลกัน (ฟังก์ชั่น built-in คือมีให้เราเรียกใช้ได้เลย)
ชื่อฟังก์ชัน | คำอธิบาย |
---|---|
type(x) | type เป็น ฟังก์ชั่นที่ไว้ตรวจสอบ ตัวแปรว่ามีชนิดข้อมูลเป็นอะไร |
int(x [,base]) |
แปลง x เป็น integer. โดยสามารถระบุฐานได้ เมื่อ x เป็น string |
long(x [,base] ) |
แปลง x เป็น long integer. โดยสามารถระบุฐานได้ เมื่อ x เป็น string |
float(x) |
แปลง x เป็น floating-point number. |
complex(real [,imag]) |
สร้าง complex number. |
str(x) |
แปลง object x เป็น a string |
repr(x) |
แปลง object x เป็น expression string. |
eval(str) |
หาค่า string เป็น object. |
tuple(s) |
แปลง s เป็น tuple. |
list(s) |
แปลง s เป็น a list. |
set(s) |
แปลง s เป็น set. |
dict(d) |
สร้างตัวแปร dictionary. d ต้องเป็น sequence of (key,value) tuples. |
frozenset(s) |
แปลง s เป็น frozen set. |
chr(x) |
แปลง integer เป็น character. |
unichr(x) |
แปลง integer เป็น Unicode character. |
ord(x) |
แปลง character ตัวเดี่ยวๆ เป็นค่า integer. |
hex(x) |
แปลง integer เป็น hexadecimal string. |
oct(x) |
แปลง integer เป็น octal string. |
ไพทอนสนับสนุน Unicode character.
ตัวอย่างการ type.py
var_dict = {}
var_dict['one'] = "This is one"
var_dict[2] = "This is two"
print (type(var_dict))
ผลที่ได้: <class 'dict'>