Python String replace() Methode
Beispiel
Ersetzen Sie das Wort "Bananen":
txt = "I like bananas"
x = txt.replace("bananas", "apples")
print(x)
Definition und Verwendung
Das replace()
Verfahren ersetzt einen bestimmten Ausdruck durch einen anderen bestimmten Ausdruck.
Hinweis: Alle Vorkommen des angegebenen Ausdrucks werden ersetzt, wenn nichts anderes angegeben ist.
Syntax
string.replace(oldvalue, newvalue, count)
Parameterwerte
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 |
Mehr Beispiele
Beispiel
Alle Vorkommen des Wortes "eins" ersetzen:
txt = "one one was a race horse, two two was one too."
x =
txt.replace("one", "three")
print(x)
Beispiel
Ersetzen Sie die beiden ersten Vorkommen des Wortes "eins":
txt = "one one was a race horse, two two was one too."
x =
txt.replace("one", "three", 2)
print(x)