I'm pretty sure my code is correct but it doesn't seem to returning the expected output:
input anti_vowel("Hey look words")
--> outputs: "Hey lk wrds"
.
Apparently it's not working on the 'e'
, can anyone explain why?
def anti_vowel(c):
newstr = ""
vowels = ('a', 'e', 'i', 'o', 'u')
for x in c.lower():
if x in vowels:
newstr = c.replace(x, "")
return newstr
You should do this:
initialize
newstr
toc
, and thenThat's because
str.replace(old, new[, max])
returns the a copy of the string after replacing the characters:So, this is the correct code:
You can also do it in a more pythonic way:
My implementation:
Another option is to forego the vowel variable and put the char's to remove in the loop.
I know there are many correct solutions on this subject but I thought to add few fun ways of solving this problem. If you come from a C++/C# or Java, you will tend to use something like compare then action using the index to remove the unwanted entry in a for loop. Python has the Remove and Del functions. Remove function uses the value and del uses the index.The pythonic solution is in the last function. Lets see how we can do that:
Here we are using the index in a for loop and del function very similar in C++:
Using the remove function:
Building new string that does not contain the unwanted chars using their indexes:
Same as in the solution in above but using the value:
How you should do it in python? Using list comprehension! It is beautiful:
Why don't you do it with regexp? According to the documentation, something like this should work:
If you're using the function often, you could compile the regexp and use the compiled version.