Метод замены строки Python
Пример
Замените слово «бананы»:
txt = "I like bananas"
x = txt.replace("bananas", "apples")
print(x)
Определение и использование
Метод replace()
заменяет указанную фразу другой указанной фразой.
Примечание. Все вхождения указанной фразы будут заменены, если не указано иное.
Синтаксис
string.replace(oldvalue, newvalue, count)
Значения параметров
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 |
Дополнительные примеры
Пример
Замените все вхождения слова «one»:
txt = "one one was a race horse, two two was one too."
x =
txt.replace("one", "three")
print(x)
Пример
Замените два первых вхождения слова «один»:
txt = "one one was a race horse, two two was one too."
x =
txt.replace("one", "three", 2)
print(x)