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

เมธอด endswith() ของสตริงใน Python

ในบทช่วยสอนนี้ เราจะเรียนรู้เกี่ยวกับเมธอด endswith() ของสตริง

เมธอด endswith() คืนค่า True หากสตริงลงท้ายด้วย substring ที่กำหนด มิฉะนั้นคืน False รับอาร์กิวเมนต์จำเป็น 1 ตัว และตัวเลือก 2 ตัว

อาร์กิวเมนต์จำเป็นคือ สตริง ที่ต้องการตรวจสอบ ตัวเลือกคือ start และ end index ค่าเริ่มต้น start=0 end=length-1

ตัวอย่าง

# เริ่มต้นสตริง
string = "tutorialspoint"
# ตรวจสอบ 'point'
print(string.endswith('point'))
# ตรวจสอบ 'Point' (case-sensitive)
print(string.endswith('Point'))
# ตรวจสอบ 'tutorialspoint'
print(string.endswith('tutorialspoint'))

ผลลัพธ์

การรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้

True
False
True

หากระบุ start และ end index endswith() จะตรวจสอบในช่วงนั้น (ไม่รวม end index)

ตัวอย่าง

# เริ่มต้นสตริง
string = "tutorialspoint"
# ตรวจสอบ 'point' ช่วง 10 ถึงสิ้นสุด
print(string.endswith('point', 10, len(string)))
# ตรวจสอบ 'point' ช่วง 8 ถึงสิ้นสุด
print(string.endswith('point', 8, len(string)))
# ตรวจสอบ 'tutorialspoint' ช่วง 0 ถึง len-1
print(string.endswith('tutorialspoint', 0, len(string) - 1))

ผลลัพธ์

การรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้

False
True
False

สรุป

endswith() ตรวจสอบท้ายสตริง case-sensitive มีพารามิเตอร์ start, end หากมีข้อสงสัย กรุณาแจ้งในส่วนความคิดเห็น