LoginSignup
2
2

More than 5 years have passed since last update.

No.034【Python】文字列の置換について①

Last updated at Posted at 2019-02-15

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

今回は、「文字列の置換」について書いていきます。

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

■ 文字列指定による置換 : replace

 The replacement of strings

>>> # string型 replace()を利用する
>>> 
>>> w = "one two three four five"
>>> 
>>> print(w.replace(" ", "-"))
one-two-three-four-five
>>> 
>>> 
>>> # 上記処理の削除方法:空文字列""にする
>>> 
>>> print(w.replace(" ", ""))
onetwothreefourfive
>>> w = "one two three four five"
>>> 
>>> print(w.replace("one", "egg"))
egg two three four five
>>> 
>>> print(w.replace("three", "mayonnaise"))
one two mayonnaise four five
>>> # 複数の文字列置換
>>> 
>>> # replace()を適用することで置換が可能
>>> 
>>> print(w.replace("two", "egg").replace("four", "salt"))
one egg three salt five
>>> 
>>> W = "one two one two one"
>>> 
>>> print(W.replace("one", "XtwoY").replace("two", "YYY"))
XYYYY YYY XYYYY YYY XYYYY
>>> 
>>> print(W.replace("two", "ZZZ").replace("one","XtwoY"))
XtwoY ZZZ XtwoY ZZZ XtwoY
>>> # ↑上記の様に、順番には注意すること
>>> # 改行文字による置換
>>> 
>>> w_lines = "one\ntwo\nthree"
>>> 
>>> print(w_lines)
one
two
three
>>> 
>>> print(w_lines.replace("\n", "-"))
one-two-three
>>> # Unix系OS:\n  Windows系:\r\n
>>> w_lines_multi = "one\ntwo\r\nthree"
>>> 
>>> print(w_lines_multi)
one
two
three
>>> 
>>> print(w_lines_multi.replace("\r\n", "-").replace("\n", "-"))
one-two-three
>>> 
>>> 
>>> print(w_lines_multi.replace("\n", "-").replace("\r\n", "-"))
one-two
-three
>>> # ↑順番によっては求める結果が得られないことがある

■ 複数文字指定による置換: translate

 Replacement of multiple string assignments: translate

>>> # str型のtranslate()を利用する

>>> # translate()に指定する変換テーブル:str.maketrans()にて作成
>>> 
>>> w = "one two one two one two"
>>> 
>>> print(w.translate(str.maketrans({"o":"O", "t":"T", "e":"E"})))
OnE TwO OnE TwO OnE TwO
>>> 
>>> 
>>> print(w.translate(str.maketrans({"o":"ZZZ", "t": None})))
ZZZne wZZZ ZZZne wZZZ ZZZne wZZZ
>>> # 辞書ではなく、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

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

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

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

2
2
2

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
2
2