Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my function partially doing what it’s supposed to do?

So I’m trying to write a Python 3 function for a challenge that takes in a string, removes the vowels and returns it without the vowels. I wrote the below code but it seems to only take out the vowels partially while leaving some untouched.

def remove_vowels(string):
    vowels = ['a','e','i','o','u']
    newstring = ""

    for letter in string:
        if letter in vowels:
            newstring = string.replace(letter,””)
        else:
             pass

    return newstring
like image 421
hell0jack Avatar asked Oct 03 '20 04:10

hell0jack


1 Answers

Your original python code with the following input

print(remove_vowels("The quick brown fox jumps over the lazy dog"))

returns "The quick brwn fx jumps ver the lazy dg"

The reason this only removes the "o" vowel is because your iterating through each vowel and updating your new string to the passed string minus the current vowel your on. So for example the first time through your for loop your "newstring" variable will be:

The quick brown fox jumps over the lzy dog

Then the next iteration your "newstring" variable will be set to

Th quick brown fox jumps ovr th lazy dog

And so on and so on. The reason my example only removes the o's is because there is no U to replace so the string replace method is never called leaving the "newstring" variables without o's.

To fix this you would just remove newstring completely and update the original string as this is it's own variable and this would technically work as is.

Although this can be compressed and refactored for better performance quite easily as you don't actually need to iterate through your string at all (nor do you need any type of new string as the passed string is it's own variable you are able to update) as pythons "String.replace" will replace ALL occurrences of the supplied substring and return the resulting string (if you don't supply a max amount of occurrences).

The following code below works

def remove_vowels(string):
    vowels = 'aeiou'
    for vowel in vowels: string = string.replace(vowel,'')
    return string

print(remove_vowels("The quick brown fox jumps over the lazy dog"))

and returns "Th qck brwn fx jmps vr th lzy dg"

like image 176
Oddity Avatar answered Sep 28 '22 05:09

Oddity