ปัญหา
สมมติว่าคุณต้องตรวจสอบต้นทางหรือปลายทางของสตริงสำหรับรูปแบบข้อความเฉพาะ รูปแบบทั่วไปคือนามสกุลไฟล์ แต่อาจเป็นอะไรก็ได้ จะแสดงวิธีการหลายวิธี
เมธอด startswith()
วิธีง่ายๆ ตรวจสอบต้นทางของสตริง คือใช้เมธอด startswith()
ตัวอย่าง
text = "Is USA colder than Australia?"
print(f"output \n {text.startswith('Is')}")
ผลลัพธ์: True
ตัวอย่าง
filename = "Hello_world.txt"
print(f"output \n {filename.startswith('Hello')}")
ผลลัพธ์: True
ตัวอย่าง
site_url = 'https://www.something.com'
print(f"output \n {site_url.startswith('http:')}")
ผลลัพธ์: False
ตัวอย่าง
print(f"output \n {site_url.startswith('https:')}")
ผลลัพธ์: True
เมธอด endswith()
วิธีง่ายๆ ตรวจสอบปลายทางของสตริง คือใช้เมธอด endswith()
ตัวอย่าง
text = "Is USA colder than Australia?"
print(f"output \n {text.endswith('?')}")
ผลลัพธ์: True
ตัวอย่าง
filename = "Hello_world.txt"
print(f"output \n {filename.endswith('.txt')}")
ผลลัพธ์: True
ตรวจสอบหลายตัวเลือกพร้อมกัน
ถ้าต้องการตรวจสอบหลายตัวเลือก ให้ส่ง tuple เข้าไป หน่วยงานทั่วไปคือตรวจสอบนามสกุลไฟล์ เช่น ต้องการ validate ไฟล์ .txt และ .csv ในไดเรกทอรี
import os
filenames = os.listdir('.')
# ตรวจสอบว่ามีไฟล์ .csv หรือ .txt อยู่ไหม
print(f"output \n {any(name.endswith(('.csv', '.txt')) for name in filenames)}")
ผลลัพธ์: True
[name for name in filenames if name.endswith(('.csv', '.txt'))]
ผลลัพธ์: รายชื่อไฟล์ที่เป็น .csv และ .txt
สำคัญ: ต้องใช้ tuple เท่านั้น
เมธอด startswith() และ endswith() รับเฉพาะ tuple หากมี list ต้องแปลงก่อน
import os
# list with choices
patterns = ['.csv', '.txt']
filenames = os.listdir('.')
# ผิด - จะ error
# any(name.endswith(patterns) for name in filenames)
# ถูก - แปลงเป็น tuple
any(name.endswith(tuple(patterns)) for name in filenames)
การประยุกต์ใช้
เมธอดทั้งสองเหมาะสำหรับรวมกับการดำเนินการอื่นๆ เช่น การกรองข้อมูล
if any(name.endswith(tuple(patterns)) for name in filenames):
# perform the logic here