No.034 [Python] 문자열의 대체 ①

3936 단어 Pythonprogramming

이번에는 '문자열의 교체' 를 쓰자.


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
또한 Qita에 투고한 내용은 언제든지 블로그에 가고 싶으니 잘 부탁드립니다.

좋은 웹페이지 즐겨찾기