8/15 sanity check for my current code


#1

Hey all, I've been trying to get this code to work for an hour or two now and am not sure how to replace the old string with a new one that has the vowel removed via my for loop.

string = "Hello aeiouy"

def anti_vowel(text):
    x = ""
    vowels = ["a", "e", "i", "o", "u"]
    for i in vowels:
        x = (text.replace(i, ""))
        print x

anti_vowel(string)

This code will print each iteration of the "for" loop without the "replace"d vowel. My problem lies in the fact that I'm not sure how to loop through each new string and then assign it to the:

x = ""

to create my final product.

I tried to do:

x = (text.replace(i, "")) + x

but that only concatenates each string to gether giving me a long list of each version of the strings with the vowels taken out.

Any ideas?


#2

I would go with a simpler approach, because you will just confuse yourself if you make it to complicated.

Problem: Remove Vowels

What are the vowels?

vowels = 'aeiou'

How do you check to see if something is in a list?

string = 'string'
for vowel in vowels:
    if vowel in string:
        print(vowel, "At index location: %s" % string.index(vowel))

Ok now that we know how to find if asomething is in something let's use it!

string = "Hello aeiouy"

def anti_vowel(text):
    vowels = 'aeiou'
    letters = list(text.lower()) # Making this a list makes it super easy to work with the string!
    new_list = []
    for index, letter in enumerate(letters):
        if letter not in vowels:
            new_list.append(letters[index])
    return ''.join(new_list)

While there are other solutions this one fits the current skill level.

Here is a simpliar more advanced solution.

def anti_vowel(text):
    return ''.join([letter for letter in list(text.lower()) if letter not in 'aeiou'])

EDIT:

forgot the lower() builtin!


#3

Thank you very much. I've got a long way to go, but when someone like you takes the time to explain everything like this it helps a ton.


#4

By the way are there other good sources for learning python??


#5

I personally found This Much easier and more explanatory than Codecademy, and it inspired me to come back here and try again.


#6

Thank you! I was cruising along until the practice problems. I haven't been able to completely solve one yet, despite lots of reading on Stack Overflow. I think I must have missed some of the basics despite getting this far...


#7

I like this solution:

def anti_vowel(text):
    vowels = ["a","A","e","E","i","I","o","O","u","U"]
    word = ""
    for i in range (len(str(text))):
        if text[i] not in vowels:
            word = word + text[i]
    return word