Python 字符串 replace() メソッド

实例

単語 "bananas" を置き換えます:

txt = "I like bananas"
x = txt.replace("bananas", "apples")
print(x)

运行实例

定義と使用方法

replace() メソッドは指定された短語を指定された短語で置き換えます。

注釈:他の内容が指定されていない場合、指定された短語のすべての現れを置き換えます。

構文

string.replace(oldvalue, newvalue, count)

パラメータの値

パラメータ 説明
oldvalue 必須。検索する文字列。
newvalue 必須。置き換える古い値の文字列。
count オプション。数字、指定する古い値が現れる回数を指定します。デフォルトはすべての現れです。

更多实例

实例

替换所有出现的单词 "one":

txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three")
print(x)

运行实例

实例

替换前两次出现的单词 "one":

txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three", 2)
print(x)

运行实例