หากต้องการลบสตริงย่อยจากท้ายสตริง ควรตรวจสอบก่อนว่าสตริงลงท้ายด้วยสตริงย่อยนั้นหรือไม่ หากใช่ ให้ slice สตริงเก็บเฉพาะส่วนที่ไม่มีสตริงย่อย ตัวอย่าง:
def rchop(string, ending):
if string.endswith(ending):
return string[:-len(ending)]
return string
chopped_str = rchop('Hello world', 'orld')
print(chopped_str)ผลลัพธ์:
Hello w
หากความเร็วไม่สำคัญ สามารถใช้ regex ได้ ตัวอย่าง:
>>> import re
>>> re.sub('orld$', '', 'Hello world')
Hello w