การค้นหาคำมีประโยชน์มาก มักมีใช้อยู่ในโปรแกรมทั่ว ๆ ไป ในการค้นหาคำมี เมท็อด ให้เลือกใช้ ได้แก่ find() และ index() เมท็อด index จะค้นหาได้เร็วกว่า find ในกรณีที่ค้นหาไม่พบคำโปรแกรมจะส่งค่า – 1 ออกมา คำสั่ง find และ index มีอาร์กิวเมนต์ให้ใช้โดยมีรูปแบบดังนี้
find(sub, [, start, [,end]])) และ
index(sub, [, start, [,end]]))
sub หมายถึง คำหรือข้อความที่ต้องการค้น
start หมายถึง ตำแหน่งเริ่มต้นที่ต้องการให้คำสั่งเริ่มค้นหา
end หมายถึง ตำแหน่งสุดท้ายที่ต้องการให้คำสั่งค้นหา
นอกจากนี้ภาษาไพธอนยังมีเมท็อด rfind() และ rindex() ให้ใช้เพื่อความสะดวก มีรูปแบบและอาร์กิวเมนต์ที่เหมือนกับเมท็อด find() และ index() แต่การค้นหาจะเริ่มจากขวามือไปซ้ายมือ ให้พิจาณาจากตัวอย่างในภาพรที่ 3.16
>>> paragraph = "It's late in the evening.\n\
She's wondering what clothes to wear.\n\
She puts on her make up.\n\
And brushes her long blonde hair.\n\
And then she asks me.\n\
Do I look alright.\n\
And I say yes, you look wonderful tonight."
>>> print paragraph.find("It's")
0
>>> print paragraph.find("She")
26
>>> print paragraph.find("man")
-1
>>> print paragraph.rfind("She")
64
>>> print paragraph.find("She",30)
64
>>> print paragraph.index("I",150, 300)
168
ภาพที่ 3.16 แสดงการคำสั่งและผลลัพธ์การค้นหาคำ
5. การค้นหาและแทนที่
การค้นหาและแทนที่ในภาษาไพธอนมีเมท็อด ให้ใช้ คือ replace() โดยมีรูปแบบการใช้อาร์กิวเมนต์ ดังนี้
replace(old, new, maxreplace)
old หมายถึง คำหรือข้อความที่ต้องการแก้
new หมายถึง คำใหม่ที่ต้องการเปลี่ยน
Maxreplace หมายถึง จำนวนครั้งสูงสุดที่ต้องการเปลี่ยน
ให้พิจาณาคำสั่งดังภาพที่ 3.17
>>> name = "Somchai, Somsak, Somkid, Somsri, Sompong, Somjai"
>>> newName = name.replace("Somjai", "Somprasong")
>>> print newName
Somchai, Somsak, Somkid, Somsri, Sompong, Somprasong
>>> newName2 = name.replace("Som", "Sak", 1)
>>> print newName2
Sakchai, Somsak, Somkid, Somsri, Sompong, Somjai
ภาพที่ 3.17 แสดงคำสั่งและผลลัพธ์การใช้คำสั่งค้นหาและแทนที่