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

โปรแกรม Python แทนที่คำด้วยดอกจัน (*) ในประโยค

ใช้โปรแกรมแทนที่คำด้วยดอกจันในประโยคเพื่อเซ็นเซอร์คำหยาบ ฯลฯ เช่น มีประโยค

"Go feed all the ducks in the lake"

และคำที่ต้องการแทนที่คือ ducks ประโยคสุดท้ายจะเป็น

"Go feed all the ***** in the lake"

ใช้ฟังก์ชัน replace ของ Python โดยตรง

ตัวอย่าง

def replaceWithAsterisk(sent, word):
    # ใช้ replace หาและแทนที่คำด้วยดอกจันจำนวนเท่าความยาวคำ
    return sent.replace(word, "*" * len(word))

sent = "Go feed all the ducks in the lake"
censored_sent = replaceWithAsterisk(sent, "ducks")
print(censored_sent)

ผลลัพธ์

Go feed all the ***** in the lake