-2

I'm beginning to learn Python and I'm trying to create a function that removes vowels from a given string. This is my Code :

def anti_vowel(text):
  li = []
  for l in text:
    li.append(l)
  while 'a' in li:
    li.remove('a')
  while 'A' in li:
    li.remove('A')
  while 'A' in li:
    li.remove('e')
  while 'e' in li:
    li.remove('E')
  while 'E' in li:
    li.remove('i')
  while 'i' in li:
    li.remove('I')
  while 'I' in li:
    li.remove('o')
  while 'o' in li:
    li.remove('O')
  while 'u' in li:
    li.remove('u')
  while 'U' in li:
    li.remove('U')
  return "".join(li)

I get the "list.remove(x): x not in list" error when I try to run it. I know this error's been already asked about here but I didn't really get the answers in those specific cases. thanks for reading and please help :)

Zerato
  • 13
  • 2

3 Answers3

1
def anti_vowel(text):  

  li = ''  
  for l in text:  
     if l.lower() not in 'aeiou':  
        li+=l  
  return li
Nishil
  • 227
  • 1
  • 9
0

You are overcomplicating it, just use a generator expresion:

def anti_vowel(text):
    return "".join(x for x in text if x not in "AEIOUaeiou")


>>> anti_vowel("asldkfoihyoihbiw")
'sldkfhyhbw'

You can use loops also:

def anti_vowel(text):
    li = []
    for l in text:
        if l not in "AEIOUaeiou":
            li.append(li)
    return "".join(li)
Netwave
  • 40,134
  • 6
  • 50
  • 93
0

You have some mis-matches in your while statement, for example:

while 'e' in li:
  li.remove('E')

If there is no 'E' but there is an 'e' this will cause a problem.

You either need to go through and make sure they are consistent.

Or you could write a small function to deal with each vowel:

def remove(letters, vowel):
    while vowel in letters:
      letters.remove(vowel)

You can then call this for each vowel.

def anti_vowel(text):
  li = []
  for l in text:
    li.append(l)

    for vowel in ['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U']:
        remove(li, vowel)

    return "".join(li)

A more Pythonic way would be to pull out the required letters, using a list comprehension or generator, as per the answer from Netware. I'm just pointing out the source of your error.

If you catch yourself repeating something lots, and copy/pasting then tweaking, you can easily miss a few places that need tweaking. Try to change the repeats into a function.

doctorlove
  • 18,872
  • 2
  • 46
  • 62