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

วิธีเช็คว่า String หรือ Substring เริ่มต้นด้วย Substring ใน Python

ใช้เมธอด startswith() ของ string class

ตัวอย่าง

>> 'hello world'.startswith('hell')
True
>>> "Harry Potter".startswith("Harr")
True
>>> 'hello world'.startswith('nope')
False

วิธี Regex (ใช้ ^ แทน start of line)

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