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

วิธีแทนที่คำที่ปรากฏครั้งสุดท้ายในสตริงใน Python

ปัญหานี้แก้ได้โดยการกลับสตริง กลับคำที่ต้องการแทนที่ แทนที่คำที่กลับแล้วด้วยคำใหม่ที่กลับแล้ว แล้วกลับสตริงกลับมา สามารถกลับสตริงด้วย slice notation [::-1] และแทนที่ด้วย str.replace(old, new, count) ตัวอย่าง:

def rreplace(s, old, new):
    return (s[::-1].replace(old[::-1], new[::-1], 1))[::-1]

rreplace('Helloworld, hello world, hello world', 'hello', 'hi')

ผลลัพธ์:

'Hello world,hello world, hi world'

วิธีอีกอย่างคือใช้ rsplit แยกสตริงครั้งเดียวจากด้านขวา แล้ว join ด้วยคำใหม่ ตัวอย่าง:

def rreplace(s, old, new):
    li = s.rsplit(old, 1)  # แยกครั้งเดียวจากขวา
    return new.join(li)

rreplace('Helloworld, hello world, hello world', 'hello', 'hi')

ผลลัพธ์:

'Hello world, hello world, hi world'