Anti_vowel - Untidy code!


#1

I solved the problem for this section but my coding is so ugly. How can I simplify the if statement to be more elegant?


def anti_vowel(text):
    sent = []
    vowels = []
    length = len(text)-1
    for i in range(length+1):
        if text[i] == "A" or text[i] == "a" or text[i] == "E" or text[i] == "e" or text[i] == "I" or text[i] == "i" or text[i] == "O" or text[i] == "o" or text[i] == "U" or text[i] == "u":
            vowels.append(text[i])
        else:
            sent.append(text[i])
    return(''.join(sent))


#2

You can initialize a blank string and then make one for loop that checks if each letter is an upper/lower case vowel. If it is, then do nothing "pass", and if it's not, add it to the end of the list.

def anti_vowel(text):
    novowel = ""
    for each in text:
        if each in "aeiouAEIOU":
            pass
        else:
            novowel += each
    return novowel

#3

Hi tekkie,

This is my version of code:

> def anti_vowel(text):
>     novowel= ""
>     vowel = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
>     for i in text:
>         if i in vowel:
>             pass
>         else:
>             novowel += i
>     return novowel

Can you please explain what exactly ELSE: does?

Pass basically doesn't let anything execute but how does it help here? If there are vowels in the text (It wont let anything execute right?) Confused. Please help.


#4

Hi Tekkie,

this is my code, it is quite sipmle.

def anti_vowel(text):
result = ""
for letter in text:
if letter not in "aeiouAEIOU" :
result = result + letter
return result

I hope it helps!


#5

These are all briliiant! Thank you everyone for the help :smiley:


#6

The for statement goes through all the characters in the string. (including spaces). The if says if it's a vowel, don't do anything, but if it's not (else), append it to the end of the string.


#7

Here is my version

def anti_vowel(x):
a =''
for i in x:
if i in "aeiouAEIOU":
x.replace(i,'')
else:
a = a+i
return a

x = 'Hey You!'
print anti_vowel(x)


#8

My solution, can probably be trimmed down a bit:

def anti_vowel(text):
    for letter in ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]:
        if letter in text:
            text=text.replace(letter,"")
    return text
    
print anti_vowel("this is a test")

ths s  tst

#9

You could remove:

a =''

and:

else:
    a = a+i

Add x=x.replace(i,'')
and just return x


#10

This is my version:

def anti_vowel(text):
    for letter in text:
        if letter in "aeiouAEIOU":
           text = text.replace(letter, "")
    return text

#11

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.