Python-string-replace
提供:Dev Guides
Python String replace()メソッド
説明
Python文字列メソッド* replace()*は、_old_の出現が_new_で置換された文字列のコピーを返します。オプションで、置換の数を_max_に制限します。
構文
以下は* replace()*メソッドの構文です-
str.replace(old, new[, max])
パラメーター
- old -これは置き換えられる古い部分文字列です。
- new -これは新しい部分文字列で、古い部分文字列を置き換えます。
- max -このオプションの引数maxが指定された場合、最初のカウントのみが置換されます。
戻り値
このメソッドは、部分文字列oldのすべての出現をnewに置き換えた文字列のコピーを返します。 オプションの引数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