Python String replace() Metoda
Przykład
Zamień słowo „banany”:
txt = "I like bananas"
x = txt.replace("bananas", "apples")
print(x)
Definicja i użycie
Metoda replace()
zastępuje określoną frazę inną określoną frazą.
Uwaga: Wszystkie wystąpienia podanej frazy zostaną zastąpione, jeśli nic innego nie zostanie określone.
Składnia
string.replace(oldvalue, newvalue, count)
Wartości parametrów
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 |
Więcej przykładów
Przykład
Zastąp wszystkie wystąpienia słowa „jeden”:
txt = "one one was a race horse, two two was one too."
x =
txt.replace("one", "three")
print(x)
Przykład
Zastąp dwa pierwsze wystąpienia słowa „jeden”:
txt = "one one was a race horse, two two was one too."
x =
txt.replace("one", "three", 2)
print(x)