Python replace() メソッド
説明
Python replace() メソッドは、文字列内の old (旧文字列) を new (新文字列) に置き換えます。3番目のパラメータ max を指定した場合、置換は max 回を超えません。
構文
replace() メソッドの構文:
str.replace(old, new[, max])
パラメータ
- old -- 置き換えられる対象の部分文字列。
- new -- 新しい文字列。old 部分文字列を置き換えるために使用します。
- max -- オプションの文字列。置換は max 回を超えません。
戻り値
文字列内の old (旧文字列) を new (新文字列) に置き換えた後に生成される新しい文字列を返します。3番目のパラメータ max を指定した場合、置換は max 回を超えません。
例
以下の例は、replace() 関数の使用方法を示しています:
例
#!/usr/bin/python
str = "this is string example....wow!!! this is really string";
print str.replace("is", "was");
print str.replace("is", "was", 3);
上記の例の出力結果は次のとおりです:
thwas was string example....wow!!! thwas was really string thwas was string example....wow!!! thwas is really string
その他の拡張
Python 文字列