Python String ganti () Metode
Contoh
Ganti kata "pisang":
txt = "I like bananas"
x = txt.replace("bananas", "apples")
print(x)
Definisi dan Penggunaan
Metode replace()
ini menggantikan frasa tertentu dengan frasa tertentu lainnya.
Catatan: Semua kemunculan frasa yang ditentukan akan diganti, jika tidak ada lagi yang ditentukan.
Sintaksis
string.replace(oldvalue, newvalue, count)
Nilai Parameter
Parameter | Description |
---|---|
oldvalue | Required. The string to search for |
newvalue | Required. The string to replace the old value with |
count | Optional. A number specifying how many occurrences of the old value you want to replace. Default is all occurrences |
Lebih Banyak Contoh
Contoh
Ganti semua kemunculan kata "satu":
txt = "one one was a race horse, two two was one too."
x =
txt.replace("one", "three")
print(x)
Contoh
Ganti dua kemunculan pertama dari kata "satu":
txt = "one one was a race horse, two two was one too."
x =
txt.replace("one", "three", 2)
print(x)