-3

What's wrong with this code? The aim is to check wether the entered string contains vowels and delete them

Here is the code:

def anti_vowel(text):
    text = str(text)
    vowel = "aeiouAEIOU"
    for i in text:
        for i in vowel.lower():
            text = text.replace('i',' ')
        for i in vowel.upper():
            text = text.replace('i',' ')
    return text

It's a lesson on Codecademy

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • You tagged this with Python 3, but the original link to Code Academy uses their Python 2 online code session. My `str.translate()` answer would have to be adjusted for Python 2, so make sure you have the right tag there. For future reference: always include your code *here*, not with a link, and include the input you used, the output you got and what you expected to get instead. – Martijn Pieters Sep 09 '14 at 12:13
  • `''.join([e for e in tgt if e.lower() not in 'aeiou'])` – dawg Sep 09 '14 at 14:03

1 Answers1

3

You are trying to replace the string with the value 'i', not the contents of the variable i.

Your code is also very inefficient; you don't need to loop over every character in text; a loop over vowel is enough. Because you already include both upper and lowercase versions, the two loops over the lowercased and uppercased versions are in essence checking for each vowel 4 times.

The following would be enough:

def anti_vowel(text):
    text = str(text)
    vowel = "aeiouAEIOU"
    for i in vowel:
        text = text.replace(i,' ')
    return text

You are also replacing vowels with spaces, not just deleting them.

The fastest way to delete (rather than replace) all vowels would be to use str.translate():

def anti_vowel(text):
    return text.translate(text.maketrans('', '', 'aeiouAEIOU'))

The str.maketrans() static method produces a mapping that'll delete all characters named in the 3rd argument.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • It'd be interesting to see the toss-up between the `maketrans` and `text.translate(dict.fromkeys(map(ord, 'AEIOUaeiou')))` – Jon Clements Sep 09 '14 at 12:07
  • @JonClements: it really should be made a function argument default instead but I didn't want to push the envelope too far here. `def anti_vowel(text, _mapping=str.maketrans('', '', 'aeiouAEIOU')): return text.translate(_mapping)`. – Martijn Pieters Sep 09 '14 at 12:08
  • Indeed... all we're missing now is `re.sub('[aeiou]', '', text, flags=RE.I)` or something - then we can have a canonical answer to the question that gets asked several times each week... – Jon Clements Sep 09 '14 at 12:12
  • @JonClements: hrm, in that case I also need to add in a Python 2 version; not sure I can squeeze that in right now. Perhaps tonight. – Martijn Pieters Sep 09 '14 at 12:13