Python - 文字列を置換する
文字列を指定して置換: 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()
外部リンク
- replace() - Python 公式ドキュメントhttps://docs.python.org/ja/3/library/stdtypes.html?highlight=replace#str.replace
正規表現で置換: re.sub()
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()
外部リンク
- re.sub() - Python 公式ドキュメントhttps://docs.python.org/ja/3/library/re.html#re.sub