Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct code to remove the vowels from a string in Python

Tags:

python

I'm pretty sure my code is correct but it doesn't seem to returning the expected output:

input anti_vowel("Hey look words") --> outputs: "Hey lk wrds".

Apparently it's not working on the 'e', can anyone explain why?

def anti_vowel(c):
    newstr = ""
    vowels = ('a', 'e', 'i', 'o', 'u')
    for x in c.lower():
        if x in vowels:
            newstr = c.replace(x, "")        
    return newstr
like image 267
KRS-fun Avatar asked Feb 05 '14 15:02

KRS-fun


People also ask

How do you remove vowels from words?

Disemvoweling, disemvowelling (see doubled L), or disemvowelment of a piece of alphabetic text is rewriting it with all the vowel letters elided. Disemvoweling is a common feature of SMS language as disemvoweling requires little cognitive effort to read, so it is often used where space is costly.

Can you remove letters from a string in Python?

You can remove a character from a Python string using replace() or translate(). Both these methods replace a character or string with a given value. If an empty string is specified, the character or string you select is removed from the string without a replacement.

How do you remove consecutive vowels in Python?

Approach: Iterate string using a loop and check for the repetitiveness of vowels in a given sentence and in case if consecutive vowels are found then delete the vowel till coming next consonant and printing the updated string.


1 Answers

Try String.translate.

>>> "Hey look words".translate(None, 'aeiouAEIOU')
'Hy lk wrds'

string.translate(s, table[, deletechars])

Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. If table is None, then only the character deletion step is performed.

https://docs.python.org/2/library/string.html#string.Template.substitute

Or if you're using the newfangled Python 3:

>>> table = str.maketrans(dict.fromkeys('aeiouAEIOU'))
>>> "Hey look words.translate(table)
'Hy lk wrds'
like image 139
Liyan Chang Avatar answered Oct 07 '22 23:10

Liyan Chang