Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การแปลง String เป็น Tuple ใน Python

Convert String to Tuple ใน Python

เมื่อต้องการแปลง String ให้เป็น Tuple สามารถใช้เมธอด map(), tuple(), int() และ split() ร่วมกันได้

คำอธิบายฟังก์ชันที่ใช้

  • map(): ใช้ฟังก์ชันที่กำหนดกับทุก Item ใน Iterable (List, Tuple) คืนค่าเป็น Iterator (Python 3)
  • int(): แปลงข้อมูลให้เป็น Integer ถ้าทำได้
  • split(): แยก String ตาม Delimiter ที่กำหนด (Default คือ Whitespace)
  • tuple(): แปลงข้อมูลให้เป็น Tuple

ตัวอย่างโค้ด

my_str_1 = "7, 8, 0, 3, 45, 3, 2, 22, 4"
print("The string is : ")
print(my_str_1)

# split ด้วย ", " แล้ว map int แล้วแปลงเป็น tuple
my_result = tuple(map(int, my_str_1.split(', ')))

print("The tuple after converting from a string is : ")
print(my_result)

ผลลัพธ์

The string is : 7, 8, 0, 3, 45, 3, 2, 22, 4
The tuple after converting from a string is : (7, 8, 0, 3, 45, 3, 2, 22, 4)

คำอธิบายขั้นตอน

  1. กำหนด String และแสดงผล
  2. split(', ') แยก String ตาม ", " ได้ List: ['7', '8', '0', '3', '45', '3', '2', '22', '4']
  3. map(int, ...) แปลงแต่ละ String เป็น Integer
  4. tuple(...) แปลง Iterator จาก map ให้เป็น Tuple
  5. เก็บผลลัพธ์และแสดง

กรณี String ไม่มี Space หลัง Comma

my_str = "7,8,0,3,45,3,2,22,4"
my_result = tuple(map(int, my_str.split(',')))
print(my_result)  # (7, 8, 0, 3, 45, 3, 2, 22, 4)

กรณี String มีตัวอักษรผสม

my_str = "a,b,c,d"
my_result = tuple(my_str.split(','))
print(my_result)  # ('a', 'b', 'c', 'd') - ไม่ต้องแปลง int