LoginSignup
1
1

More than 3 years have passed since last update.

【Python】文字列から任意の文字を置換する

Posted at

環境

OS : MacOS Mojave
Python 3.7.2

re.sub()を使う

正規表現を使って文字列置換を行います。
基本形は以下の通りです。

re.sub("[置換したい文字]", "置換後の文字", "置換対象の文字列")

まず、置換したい文字が一文字だった場合を以下に示します。

>>import re
>>re.sub("[a]", "あ", 'abcdefg')
'あbcdefg'
>>re.sub("[a]", "あ", 'aaabbbccc')
'あああbbbccc'

abcdefg、aaabbbcccのaを全て"あ"に変換しています。

置換したい文字は二文字以上だと、それぞれの文字を置換後の文字にします。

>>import re
>>re.sub("[aceg]", "あ", 'abcdefg')
'あbあdあfあ'
>>re.sub("[ac]", "あ", 'aaabbbccc')
'あああbbbあああ'
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1