Anti_vowel - almost done!


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/2?curriculum_id=4f89dab3d788890003000096#


Hi, I have one, last problem. I can't remove the "" when I'm returnings the letter


def anti_vowel(x):

    text = []
    for i in x:
        if i == 'a' or i=='e' or i == 'i' or i == 'u' or i=='o':
            x.strip(i)
        else:
            text.append(i)
    return text


#2

Hah when I was doing this code, I did a reverse code xD

ef anti_vowel(x):

    text = []
    for i in x:
        if i == 'a' or i=='e' or i == 'i' or i == 'u' or i=='o':
            x.strip(i)
        else:
            k=0
            text.insert(k,i)
            k+=1
    return text

I'm great xD


#3

I've done the exercise.

def anti_vowel(x):
    text = ""
    for i in x:
        if i not in "aAeEiIoOuU":
            text=text+i
    return text

I'm not really sure why does text=text+i works, but text+=i dont


#4

Strings are immutable. text += i is a mutation.

text += i   # cannot mutate text

text + i    # is an expression to evaluate

text = ...  # is an assignment that re-purposes the variable

#5

Ahh, thanks
(making 20 letters)


#6

Very clever way to go about this! Thanks, I totally forgot about "not in"


#7

Optionally, we can use a working list and join the return value. Lists are mutable.

def anti_vowel(x):
    result = []
    for i in x:
        if i.lower() not in "aeiou":
            result.append(i)
    return ''.join(result)

Python also lets us remove elements by value:

old_str = "The rain in Spain falls mainly in the plains"
s = list(old_str)
for x in 'AaEeIiOoUu':
    while x in s:
        s.remove(x)
print ''.join(s)

 # Th rn n Spn flls mnly n th plns

This is a little trickier since if uses a nested loop to search for each instance of the letter to remove. Not the most efficient.

This is another method that is greedy (global) and replaces all instances of old with new.

old_str = "The rain in Spain falls mainly in the plains"
new_str = old_str

for x in 'AaEeIiOoUu':
     new_str = new_str.replace(x, '')

print new_str    # Th rn n Spn flls mnly n th plns

and without preserving case:

new_str = old_str.lower()
for x in 'aeiou': 
    new_str = new_str.replace(x, '')

print new_str     # th rn n spn flls mnly n th plns

Using the built-ins here is just for added practice, in addition to algorithm practice intended in this exercise. There are many ways to do the same thing in Python. We've only touched on a handful of ways to filter text. Remember to go back and review, then expand your knowledge in each concept.


#8

That is pretty awesome. Thank you.


#9

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