HOME
文字列を指定して置換する場合は replace 関数を使います。第一引数に置換元文字列、第二引数に置換先文字列を指定します。
文字列を指定して置換する場合は replace
関数を使います。第一引数に置換元文字列、第二引数に置換先文字列を指定します。
date = "2022-04-12"
print(date.replace("-", "/")) # 2022/04/12
replace()
第三引数 count
を含めると、最大置換回数を指定できます。最大置換回数を超える場合、後続の置換対象文字は置換されません。
date = "2022-04-12"
print(date.replace("-", "/", 1)) # 2022/04-12
replace()
re.sub
関数では第一引数に正規表現のパターン、第二引数に置換先文字列、第三引数に処理対象の文字列を指定します。re.sub
関数は、標準ライブラリの re
モジュールを import
して使います。
import re
text = "abc123"
result = re.sub(r"[a-z]", "0", text)
print(result) # 000123
re.sub()
replace()
関数と同じく第四引数 count
に最大置換回数を指定できます。
import re
text = "abc123"
result = re.sub(r"[a-z]", "0", text, 2)
print(result) # 00c123
re.sub()