LoginSignup
0
0

More than 1 year has passed since last update.

Python 文字列から特定文字列を取り除く

Posted at

はじめに

特定文字列は英語の母音として設定し、取り除く方法を正規表現を使用する/使用しないパターンの2種を紹介します。

方法1 正規表現を使わない

入力文字列をforで回し、各文字が特定文字列に合致しないものをjoinで連結する

py
txt = 'Hello World'
print(''.join(c for c in txt if c not in 'aeiouAEIOU'))

実行結果
Hll Wrld

方法2 正規表現を使う

正規表現パターンで文字列を分割し、リストをjoinで1つの文字列に連結する

py
import re
c = 'Hello World'
print(''.join(re.split('a|e|i|o|u|A|E|I|O|U', c)))

実行結果
Hll Wrld

ちなみに今回は関数splitでの処理を紹介していますが、subでもほとんど同じようことができます。

正規表現の参考資料:
Pythonの正規表現モジュールreの使い方(match、search、subなど)

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