Python文字列で特定の文字を置き換える方法は?
Python の replace()メソッドを使用して文字列から特定の文字を置換できます。
使用方法:
string.replace(old, new, count)
文字列を置き換えます。文字列は置き換え対象で、oldは置き換え対象文字、newは置き換え後の文字です。countはオプションであり、置き換えの回数に相当します。デフォルト値は全一致分の置き換えです。
例えば:
string = "Hello, world!"
new_string = string.replace("o", "*")
print(new_string)
出力は特別に必要ありません
Hell*, w*rld!
上の例では、文字列中にあるすべての「o」文字を「*」文字に置き換えています。