-1

I'm working through the Python course on codecademy and trying to create a python function that removes vowels in a string and returns the newly modified string.However the function returns the string without any modification (i.e. if I call anti_vowel("abcd") it returns "abcd")

After using a print statement it appears the for loop only runs once, irrespective of the length of the string.

def anti_vowel(string):
    for t in string:
        if(t.lower()=='a' or t.lower()=='e' or t.lower()=='i' or t.lower()=='u'):
            string.replace(t, " ")
            print "test"
        print string
        return string
cs95
  • 379,657
  • 97
  • 704
  • 746
  • strings are immutable in python, replace returns new one. Use `string = string.replace(...)` – Sav Jun 11 '19 at 06:17

2 Answers2

0

Strings in Python are immutable, so you will need to make an assignment back to the original string with the replacement on the RHS:

if (t.lower()=='a' or t.lower()=='e' or t.lower()=='i' or t.lower()=='u'):
    string = string.replace(t, " ")

But, you could also just re.sub here:

string = re.sub(r'[aeiou]+', '', string, flags=re.IGNORECASE)
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
-1

You have the return statement inside the for a loop that is why your code is your loop is executing exactly once. Place it outside the loop and your code will work fine.

def anti_vowel(string):
    for t in string:
        if(t.lower()=='a' or t.lower()=='e' or t.lower()=='i' or t.lower()=='u'):
            string.replace(t, " ")
        print "test"
    print string
    return string

For replacing the vowel characters, you cannot replace in the existing variable as strings in python are immutable. You can try this

def anti_vowel(string):
    for t in string:
        if(t.lower()=='a' or t.lower()=='e' or t.lower()=='i' or t.lower()=='u'):
            string=string.replace(t, " ")
        print "test"
    print string
    return string
bumblebee
  • 1,811
  • 12
  • 19