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

วิธีตรวจสอบว่าสตริงขึ้นต้นด้วย XYZ ใน Python

Python มีเมธอด startswith(string) ในคลาสสตริง เมธอดนี้รับสตริงคำนำหน้า (prefix) ที่ต้องการค้นหา และถูกเรียกบนออบเจกต์สตริง ใช้งานได้ดังนี้:

>>> 'hello world'.startswith('hell')
True
>>> 'hello world'.startswith('nope')
False

อีกวิธีหนึ่งคือใช้ re.search('^' + prefix, string) จากโมดูล re (regular expression) Regex ตีความ ^ ว่าเป็นจุดเริ่มบรรทัด ดังนั้นหากต้องการค้นหาคำนำหน้า ให้ทำดังนี้:

>>> import re
>>> bool(re.search('^hell', 'hello world'))
True
>>> bool(re.search('^nope', 'hello world'))
False