LoginSignup
0
1

More than 5 years have passed since last update.

No.035【Python】文字列の置換について②

Posted at

python-logo-master-v3-TM-flattened.png

前回に引き続き、「文字列の置換」について書いていきます。

I'll write continuousy about the replacement of strings in python" on this page.

■ 正規表現による置換: re.sub / re.subn

 The replacement by Regular expression:re.sub, re.subn

>>> # 置換元文字列と完全一致の場合、置換される(replace()・translate()関数)
>>> # 完全一致出ない置換の場合は、reモジュール sub()関数を利用する
>>> 
>>> import re
>>> 
>>> w = 'aaa@egg.com bbb@salt.com ccc@mastard.com'
>>> 
>>> print(re.sub("[a-z]*@", "ABC@", w))
ABC@egg.com ABC@salt.com ABC@mastard.com
>>> 
>>> 
>>> # replace()同様、第四引数(count)に最大置換回数の指定が可能
>>> 
>>> print(re.sub('[a-z]*@', 'ABC@', w, 2))
ABC@egg.com ABC@salt.com ccc@mastard.com
>>> # 複数の文字列を同文字列へ置換
>>> 
>>> import re
>>> 
>>> w = 'aaa@xxx.com bbb@yyy.com ccc@zzz.com'
>>> 
>>> print(re.sub("[xyz]", "1", w))
aaa@111.com bbb@111.com ccc@111.com
>>> # ↑複数の異なる文字を同じ文字列に置換する場合に利用する
>>> # |で区切るといずれかのパターンにマッチする
>>> # 正規表現の特殊文字利用も可、文字列をそのまま指定しても可能
>>> # 複数の異なる文字列を同じ文字列に置換する場合に利用する
>>> 
>>> import re
>>> 
>>> w = 'aaa@xxx.com bbb@yyy.com ccc@zzz.com'
>>> 
>>> print(re.sub('aaa|bbb|ccc', 'ABC', w))
ABC@xxx.com ABC@yyy.com ABC@zzz.com
>>> # 一致箇所を使った置換
>>> # パターンの一部を()で囲む:()内の一致する文字列を利用することが可能
>>> 
>>> print(re.sub('([a-z]*)@', '\\1-123@', w))
aaa-123@xxx.com bbb-123@yyy.com ccc-123@zzz.com
>>> 
>>> 
>>> print(re.sub('([a-z]*)@', r'\1-123@', w))
aaa-123@xxx.com bbb-123@yyy.com ccc-123@zzz.com
>>> 
>>> 
>>> # ↑ \1 が()に一致した箇所に対応。()が吹く風の場合は \2,\3とする
>>> # ↑ '',””で囲まれた文字列は、\\1の様に\をエスケープすることが必要
>>> # ↑ r""の様に先頭にrをつけるraw文字列の場合、\1で問題ない
>>> # 置換箇所の個数取得
>>> # 置換された文字列と置換部分の個数とタプルを返す

>>> t = re.subn('[a-z]*@', 'ABC@', w)
>>> 
>>> print(t)
('ABC@xxx.com ABC@yyy.com ABC@zzz.com', 3)
>>> 
>>> print(type(t))
<class 'tuple'>
>>> 
>>> print(t[1])
3
>>> # 辞書ではなく、3つの文字列を引数として指定することも可能
>>> 
>>> print(w.translate(str.maketrans('ow', 'ZW', 'n')))
Ze tWZ Ze tWZ Ze tWZ
>>> # 以下の場合、第一・第二引数の文字列の長さは一致が必要
>>> # 置換先文字列に長さ2つ以上文字列は指定不可
>>> 
>>> print(w.translate(str.maketrans('ow', 'ZZW', 'n')))
Traceback (most recent call last):
  File "<pyshell#88>", line 1, in <module>
    print(w.translate(str.maketrans('ow', 'ZZW', 'n')))
ValueError: the first two maketrans arguments must have equal length

■ 位置指定による置換・挿入: slice

 The replacement and insertion by tab control specification:slice

>>> # スライスによる分割により任意の文字列と連結
>>> # →指定位置が置換された新たな文字列が作成できる

>>> w = "'abcdefghijklmn'"
>>> 
>>> print(w[:5] + "XXX" + w[8:])
'abcdXXXhijklmn'

>>> # 文字列に別の文字列を連結しているだけ
>>> # → 文字数の一致は不要
>>> 
>>> print(w[:5] + '-' + w[8:])
'abcd-hijklmn'
>>> # 任意の位置に別の文字列を挿入し、新たな文字列の作成も可能
>>> 
>>> print(s[:5] + '*******' + s[5:])
Traceback (most recent call last):
  File "<pyshell#90>", line 1, in <module>
    print(s[:5] + '*******' + s[5:])
NameError: name 's' is not defined
>>> print(w[:5] + '*******' + w[5:])
'abcd*******efghijklmn'

随時に更新していきますので、
定期的な購読をよろしくお願いします。
I'll update my article at all times.
So, please subscribe my articles from now on.

本記事について、
何か要望等ありましたら、気軽にメッセージをください!
If you have some requests, please leave some messages! by You-Tarin

また、「Qiita」へ投稿した内容は、随時ブログへ移動して行きたいと思いますので、よろしくお願いします。

0
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
0
1