-5

I wrote a function to remove vowels in a given string.

def anti_vowel(text):
    text = list(text)
    vowel = 'aeiou'
    for letter in text:
        if letter.lower() in vowel:
            text.remove(letter)
    return ''.join(text)

It doesn't remove all of the vowels, when I input 'Hey look Words!' the output is 'Hy lk Words!'

Why doesn't this code remove all vowels in the input?

James Sapam
  • 16,036
  • 12
  • 50
  • 73
user3266450
  • 9
  • 1
  • 2
  • 1
    See [this](http://arshajii.com/coding-faqs/conc-list-mod.html). – arshajii Feb 03 '14 at 15:53
  • 8
    Seriously, you post an identical code, from a question with 50 upvotes, which has the same output..... How can you miss that. You even named the function the same. What the heck, lol. – luk32 Feb 03 '14 at 15:53

4 Answers4

2

Altering the list you are looping over could lead into undesired results. Make a copy of it first:

for letter in text[:]:

Using [:] is called list slicing. From Python Docs:

All slice operations return a new list containing the requested elements. This means that the following slice returns a shallow copy of the list a
>>> a[:]

The are also other ways to make a copy, like:

list(text)

Read more aboout how to make a copy of a list.

Community
  • 1
  • 1
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
2

You're modifying a list during the iteration. One solution is to iterate over a copy of list. The other solution is to avoid side-effects and go functional:

def anti_vowel(text):
    return "".join(c for c in text if c.lower() not in 'aeiou')
Nigel Tufnel
  • 11,146
  • 4
  • 35
  • 31
1

You can use a regex pattern that excludes all vowels with the hat ^

import re
pattern = '([^aeiou])'
str_ = "no vowels"
no_vowel_list = re.findall(pattern,str_)
print no_vowel_list
user1749431
  • 559
  • 6
  • 21
0

Here is a solution:

def anti_vowel(text):
    text = list(text)
    result = list()
    for letter in text:
        if letter.lower() not in 'aeiou':
            result.append(letter)
    return ''.join(result)

s = 'Hey look Words!'
print anti_vowel(s)

Output:

Hy lk Wrds!
James Sapam
  • 16,036
  • 12
  • 50
  • 73