Devdit
 

ค้นหา string ใน array Python ด้วย for และ if

1.1K

ค้นหา string ใน array Python บทความนี้สอนเขียนโค้ดค้นหา string หรือข้อความใน array ด้วยภาษา Python โดยสร้าง list ชื่อ colors และใช้คำสั่ง for วนลูปตัวแปร list เพื่อค้นหา string สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่าง ค้นหา string ใน array Python ด้วย for และ if

colors = ['red', 'green', 'blue']
find = 'green'
res = [s for s in colors if find in s]

if len(res) > 0:
  print('พบ string',find,'ใน array colors')
else:
  print('ไม่พบ string',find,'ใน array colors')

ผลลัพธ์

พบ string green ใน array

คำอธิบาย

ค้นหา string ใน array Python ด้วย for และ if จากตัวอย่างโค้ดสร้างตัวแปรชื่อ colors ชนิด list และตัวแปรชื่อ find เก็บ string ที่จะค้นหาคือ ‘green’ จากนั้นใช้คำสั่ง [s for s in colors if find in s] ซึ่งจะเป็นการวนลูปจากตัวแปร colors พร้อมกับค้นหา string ตัวแปร find ใน list colors พร้อมเก็บผลลัพธ์ที่ตัวแปร res จากนั้นใช้คำสั่ง if len(res) > 0 กรณีตัวแปร res มีจำนวนข้อมูลมากกว่า 0 แปลว่า พบข้อมูลให้ทำงานใน if หากเท่ากับ 0 แปลว่าไม่พบให้ทำงานใน else

แก้ไข 1 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ