LoginSignup
5
3

More than 5 years have passed since last update.

'ある文字'を'ある文字列'から削除する。

Last updated at Posted at 2015-10-27

例'I am learning Python.'から母音'a,e,i,o,u'を削除して'm lrnng Pythn.'を出力する。

ある文字(達)は母音の vowels = ['a','e','i','o','u','A','I','U','E','O']
ある文字列は'I am learning Python.'

example.py
def anti_vowel(text):
    vowels = ['a','e','i','o','u','A','I','U','E','O']
    new_text =[]
    for i in text:
        new_text.append(i)
        for j in vowels:
            if i == j:
                new_text.remove(j)
    return ''.join(new_text)
print anti_vowel('I am learning Python.')
# m lrnng Pythn.

こういうのも。

example2.py
def anti_vowel(text):
        new_text = ""
        vowels = "aeiouAEIOU"
        for i in text:
            if i not in vowels:
                new_text += i
        return new_text
print anti_vowel('I am learning Python.')

一行で書くと

example3.py
def anti_vowel(text):
    return ''.join([new_text for new_text in list(text) if new_text not in 'aeiouAEIOU'])
print anti_vowel('I am learning Python.')

正規表現(※メモ:要勉強)をつかうと以下のように書ける。

example.py
import re
s='I am learning Python.'
print re.sub('[aeiouAEIOU]', '', s)
#Or
print s.translate(None, 'aeiouAEIOU')
#Or
print filter(lambda c: c.lower() not in 'aeiou', s)

@knoguchiさん、ありがとうございます!

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