Remove'some character'from'some string'.

Example Remove the vowels'a, e, i, o, u'from'I am learning Python.'And output'm lrnng Pyth n.'.

Some letters (s) are vowels = ['a','e','i','o','u','A','I','U','E','O' ] Some strings are'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.

This is also the case.

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.')

If you write in one line

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.')

Using regular expressions (* memo: study required), you can write as follows.

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)

Thank you @knoguchi!

Recommended Posts

Remove'some character'from'some string'.
String format
String format 2
String summary 1
raw string
Python string