6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

python3系で正規表現を使わずに文字列の複数の文字を置き換えたいとき

Last updated at Posted at 2017-08-02

#python3系で文字列の複数の文字を置き換えたいとき

###使用する命令・関数・メソッド

  • dict.fromkeys()
  • str.maketrans()
  • str.translate()

###サンプル

sample.py
lst = ['1', '2', '3']
delete_for_str = str.maketrans(dict.fromkeys(lst, "<ok>")) #第1引数: イテレータ, 第2引数: 置換後の文字列
oldstr = '1ho2ge3'
newstr = oldstr.translate(delete_for_str)
print(newstr)
#出力結果:
#<ok>ho<ok>ge<ok>
6
5
1

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
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?