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

วิธี Replace ทุก Occurrence ของ String ใน Python

ใช้เมธอด replace(old, new) ของ string class

ตัวอย่าง

>> 'no one knows how'.replace('no', 'yes')
'yes one kyesws how'
>>> "chihuahua".replace("hua", "hah")
'chihahhah'

ใช้ re.sub() สำหรับ pattern ซับซ้อน

>> import re
>>> re.sub('hua', 'hah', 'chihuahua')
'chihahhah'