8/15 Anti_Vowel loop(HELP)


#1

def anti_vowel(text):
anti=""
for i in text:
for o in "aeiouAEIOU":
if i!=o:
anti.append(i)
return anti

I want to use two loops to get the anti_vowel. But failed.
I need some help, thx.


#2

Strings are immutable so use a list instead, also you have to break the loop if you find a vowel and then after the second loop is done for that letter you then add the letter to the list.

def anti_vowel(word):
    temp = []
    for letter in word.lower():
        for vowel in "aeiou":
            a_vowel = False
            if letter == vowel:
                a_vowel = True
                break
        if not a_vowel:
            temp.append(letter)
    return ''.join(temp)

As you can see because you want to use two loops you have a bunch of code, but it does work.

You can change your code a bit and shorten it quite a bit.

def anti_vowel(word):
    return ''.join((letter for letter in word.lower() if letter not in 'aeiou'))

EDIT:

You can also use regular expresions to do this too,

import re
def anti_vowel(word):
    return re.sub('[aeiou]', '', word.lower())

There are a few more ways you can do it, but it really is a matter of opinion on which is best.


#3

You may use concatenation:

anti += i

instead of

anti.append(i)

And that's right, without True/False variation flag, double-loop gives multiplicative result:
print anti_vowel("I wanna be free!")
=> IIIIIIIII wwwwwwwwwwaaaaaaaaannnnnnnnnnnnnnnnnnnnaaaaaaaaa bbbbbbbbbbeeeeeeeee ffffffffffrrrrrrrrrreeeeeeeeeeeeeeeeee!!!!!!!!!!


#4

Here is your mistake. The only way you dont append a letter is if none of the letters in "aeiouAEIOU" are equal to it, which obviously can't happen.

If for example i = "a":

 for o in "aeiouAEIOU":
    if i!=o:
    anti.append(i)

The loop starts with "a" as your o. i is equal to "a" so it doesn't get appended. But then o changes to "e" which doesn't equal "a" and i will be appenden to anti. Next is "i" which also doesn' equal "a" and so on until "a" got appended for every letter in "aeiouAEIOU" except "a".


#5

def anti_vowel(text):
text=list(text)
test=""
for i in text:
if i not in ["a","e","i","o","u","A","E","I","O","U"]:
test+=i
return test

try this!


#6

I dont think you need this line: text=list(text), but otherwise, nice code :slight_smile:


#7

Or this one:
text = input('\nYour text here: ')
vovel = 'aeiouAEIOU'

def anti_vovel(text):
result = ''
for letters in text:
if letters not in vovel:
result += letters
return result

print(anti_vovel(text))