Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

環境

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あああ'
sino20023
某日系企業でデータサイエンティストやってます。大学時代はバイオインフォマティクスの研究をしていました。よろしくお願いします。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした