Python String rindex()เมธอด
ตัวอย่าง
ตำแหน่ง สุดท้ายของสตริง "casa" อยู่ที่ไหนในข้อความ :
txt = "Mi
casa, su casa."
x = txt.rindex("casa")
print(x)
ความหมายและการใช้งาน
วิธีrindex()
ค้นหาการเกิดขึ้นล่าสุดของค่าที่ระบุ
วิธี การrindex()
ทำให้เกิดข้อยกเว้นหากไม่พบค่า
วิธี การrindex()
เกือบจะเหมือนกับ
rfind()
วิธีการ ดูตัวอย่างด้านล่าง
ไวยากรณ์
string.rindex(value, start, end)
ค่าพารามิเตอร์
Parameter | Description |
---|---|
value | Required. The value to search for |
start | Optional. Where to start the search. Default is 0 |
end | Optional. Where to end the search. Default is to the end of the string |
ตัวอย่างเพิ่มเติม
ตัวอย่าง
ตำแหน่งสุดท้ายของตัวอักษร "e" อยู่ที่ไหนในข้อความ:
txt = "Hello, welcome to my world."
x = txt.rindex("e")
print(x)
ตัวอย่าง
ตำแหน่งใดในข้อความที่เกิดครั้งสุดท้ายของตัวอักษร "e" เมื่อคุณค้นหาระหว่างตำแหน่ง 5 ถึง 10 เท่านั้น:
txt = "Hello, welcome to my world."
x = txt.rindex("e",
5, 10)
print(x)
ตัวอย่าง
หากไม่พบค่า เมธอด rfind() จะคืนค่า -1 แต่เมธอด rindex() จะทำให้เกิดข้อยกเว้น:
txt = "Hello, welcome to my world."
print(txt.rfind("q"))
print(txt.rindex("q"))