Pythonのreplace関数の使い方は?

Pythonでは、replace関数が文字列内の部分文字列を置換するために使用されます。

replace関数の基本構文は次の通りです:

new_string = string.replace(old, new, count)

stringは置換操作を行う対象の文字列で、oldは置換される部分文字列、newは置換後の新しい部分文字列、countはオプションのパラメータで、最大置換回数を表します。

以下、サンプルコードを示す。

string = "Hello, World!"
new_string = string.replace("Hello", "Hi")
print(new_string)  # 输出: Hi, World!

上記の例では、文字列の中にある”Hello”を”Hi”に置き換えます。

countを指定しない場合、すべての一致するサブストリングがデフォルトで置換されます。countを指定した場合、最大でcount回まで置換されます。

以下はサンプルコードです。

string = "Hello, Hello, Hello!"
new_string = string.replace("Hello", "Hi", 2)
print(new_string)  # 输出: Hi, Hi, Hello!

上記の例では、文字列内の最初の2つの「Hello」を「Hi」に置き換え、3つ目の「Hello」は置き換えられませんでした。

注意すべき点は、replace関数は新しい文字列を返し、元の文字列は変更されないことです。 元の文字列を変更したい場合は、置換後の結果を元の文字列変数に代入する必要があります。

サンプルコードは以下の通りです:

string = "Hello, World!"
string = string.replace("Hello", "Hi")
print(string)  # 输出: Hi, World!
bannerAds