บางครั้งข้อมูลที่ได้มาอาจเป็นสตริง แต่โครงสร้างภายในเป็นลิสต์ของ Python บทความนี้จะสาธิตวิธีแปลงสตริงที่ห่อหุ้มลิสต์ให้กลายเป็นลิสต์จริงเพื่อนำไปประมวลผลต่อ
ใช้ eval()
ฟังก์ชัน eval() จะประเมินค่าที่ส่งเข้าไป ดังนั้นเราส่งสตริงที่กำหนดให้ eval() เพื่อให้คืนค่าเป็นลิสต์ของ Python
ตัวอย่าง
stringA = "['Mon', 2,'Tue', 4, 'Wed',3]" # สตริงที่กำหนด
print("Given string : \n", stringA)
# ตรวจสอบชนิด
print(type(stringA))
# ใช้ eval
res = eval(stringA)
# ผลลัพธ์
print("The converted list : \n", res)
# ตรวจสอบชนิด
print(type(res))
ผลลัพธ์
Given string : ['Mon', 2,'Tue', 4, 'Wed',3] The converted list : ['Mon', 2, 'Tue', 4, 'Wed', 3]
ใช้ ast.literal_eval()
วิธีนี้ใช้ฟังก์ชัน literal_eval() จากโมดูล ast ซึ่งปลอดภัยกว่า eval() เพราะประเมินเฉพาะ literal เท่านั้น
ตัวอย่าง
import ast
stringA = "['Mon', 2,'Tue', 4, 'Wed',3]" # สตริงที่กำหนด
print("Given string : \n", stringA)
# ตรวจสอบชนิด
print(type(stringA))
# ใช้ literal_eval
res = ast.literal_eval(stringA)
# ผลลัพธ์
print("The converted list : \n", res)
# ตรวจสอบชนิด
print(type(res))
ผลลัพธ์
Given string : ['Mon', 2,'Tue', 4, 'Wed',3] The converted list : ['Mon', 2, 'Tue', 4, 'Wed', 3]
ใช้ json.loads()
ฟังก์ชัน loads() จากโมดูล json สามารถแปลงสตริง JSON ให้เป็นลิสต์ของ Python ได้ (สตริงต้องใช้ double quotes)
ตัวอย่าง
import json
stringA = '["Mon", 2,"Tue", 4, "Wed",3]' # สตริงที่กำหนด (ใช้ double quotes)
print("Given string : \n", stringA)
# ตรวจสอบชนิด
print(type(stringA))
# ใช้ loads
res = json.loads(stringA)
# ผลลัพธ์
print("The converted list : \n", res)
# ตรวจสอบชนิด
print(type(res))
ผลลัพธ์
Given string : ["Mon", 2,"Tue", 4, "Wed",3] The converted list : ['Mon', 2, 'Tue', 4, 'Wed', 3]