Python文字列replace()メソッド
例
「バナナ」という単語を置き換えます。
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)
例
「one」という単語の最初の2つを置き換えます。
txt = "one one was a race horse, two two was one too."
x =
txt.replace("one", "three", 2)
print(x)