Python3-string-replace

提供:Dev Guides
移動先:案内検索

Python 3-String replace()メソッド

説明

  • replace()*メソッドは、古いものが新しいものに置き換えられた文字列のコピーを返します。オプションで、置き換えの数を最大に制限します。

構文

以下は* replace()*メソッドの構文です-

str.replace(old, new[, max])

パラメーター

  • old -これは置き換えられる古い部分文字列です。
  • new -これは新しい部分文字列で、古い部分文字列を置き換えます。
  • max -このオプションの引数maxが指定された場合、最初のカウントのみが置換されます。

戻り値

このメソッドは、部分文字列oldのすべての出現をnewに置き換えた文字列のコピーを返します。 オプションの引数maxが指定された場合、最初のカウントの出現のみが置き換えられます。

次の例は、replace()メソッドの使用法を示しています。

#!/usr/bin/python3

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