12

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
0

13 Answers 13

22

The function str.replace(old, new[, max]) doesn't change the c string itself (with respect to c you call). It just returns a new string in which the occurrences of old have been replaced with new. So newstr just contains a string replaced by last vowel in c string that is the o and hence you are getting "Hey lk wrds", which is same as "Hey look words".replace('o', '').

I think you can simply write anti_vowel(c) as:

''.join([l for l in c if l not in vowels]);

What I am doing is iterating over string and if a letter is not a vowel then only include it into list(filters). After filtering I join the list back to a string.

Sign up to request clarification or add additional context in comments.

8 Comments

Shouldn't it be [l for l in c if l not in vowels]?
You can leave out the [] and use the implicit Generator instead of this intermediate List.
@ChrisWesseling see stackoverflow.com/questions/9060653/… for a ''.join() call it is faster to use a list comprehension instead of a generator expression.
@GrijeshChauhan :-) I was just in the process of timeit'ing it
A programming newbie here. Could you guys pls explain to me this way expression: "[l for l in c if l not in vowels]" ? I know about for loops,if etc. but how could u pull this one out ? Thanks in advance.
|
17

Why don't you do it with regexp? According to the documentation, something like this should work:

import re

def anti_vowel(s):
    result = re.sub(r'[AEIOU]', '', s, flags=re.IGNORECASE)
    return result

If you're using the function often, you could compile the regexp and use the compiled version.

1 Comment

This seem like the best approach to me (only commenting because of the errent down vote)
11

Try String.translate.

>>> "Hey look words".translate(None, 'aeiouAEIOU')
'Hy lk wrds'

string.translate(s, table[, deletechars])

Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. If table is None, then only the character deletion step is performed.

https://docs.python.org/2/library/string.html#string.Template.substitute

Or if you're using the newfangled Python 3:

>>> table = str.maketrans(dict.fromkeys('aeiouAEIOU'))
>>> "Hey look words".translate(table)
'Hy lk wrds'

3 Comments

This is best way I think, I prefer to use tools provided by language over writing a new.
Nice, but this doesn't work in Python3. 'test'.translate(str.maketrans('aeiouAEIOU', '-'*10)) produces t-st, but can't replace with None in Python 3
Updated for Python 3. Agree that it's slightly more awkward.
8

Another option is to forego the vowel variable and put the characters to remove in the loop.

    def anti_vowel(text):
        for i in "aeiouAEIOU":
            text = text.replace(i,"")
        return text

    print anti_vowel("HappIEAOy")

Comments

5

You should do this:

initialize newstr to c, and then

for x in c.lower():
    if x in vowels:
        newstr = newstr.replace(x, "")

That's because str.replace(old, new[, max]) returns the a copy of the string after replacing the characters:

The method replace() returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max.

So, this is the correct code:

def anti_vowel(c):
    newstr = c
    vowels = ('a', 'e', 'i', 'o', 'u')
    for x in c.lower():
        if x in vowels:
            newstr = newstr.replace(x,"")

    return newstr

You can also do it in a more pythonic way:

''.join([x for x in c if x not in vowels])

Comments

3
vowels = ('a', 'e', 'i', 'o', 'u', 'A', 'I', 'E', 'O', 'U')

for char in text:

    if char in vowels:

        text = text.replace(char, '')

return text

2 Comments

This is really interesting! One of the simplest I guess for a new comer.
The only issue for me personally, is that when I try to do that not in a function, and not with "return", then I get the word repeated over and over again until it has no vowels...while I would rather get the result directly.
3

One more simpler way can be extracting the non-vowel characters from string and returning them.

def anti_vowel(text):
    newstring=""
    for i in text:
        if i not in "aeiouAEIOU":
            newstring=newstring+i
    text=newstring
    return text

1 Comment

one thing, you can return newstring instead of text
3

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++:

def remove_vol(str1):
     #list2 = list1 # this won't work bc list1 is the same as list2 meaning same container#
    list1 = list(str1)
    list2 = list(str1)
    for i in range(len(list1)):
        if list1[i] in volwes:
            vol = list1[i]
            x = list2.index(vol)
            del list2[x]
    print(list2)

Using the remove function:

def remove_vol(str1): 
      list1 = list(str1)
      list2 = list(str1)
      for i in list1:
          if i in volwes:
              list2.remove(i)
      print(list2)

Building new string that does not contain the unwanted chars using their indexes:

def remove_vol(str1):  
    list1 = list(str1)
    clean_str = ''
    for i in range(len(list1)):
        if list1[i] not in volwes:
            clean_str += ''.join(list1[i])
    print(clean_str)

Same as in the solution in above but using the value:

def remove_vol(str1):
    list1 = list(str1)
    clean_str = ''
    for i in list1:
        if i not in volwes:
            clean_str += ''.join(i)
    print(clean_str)

How you should do it in python? Using list comprehension! It is beautiful:

def remove_vol(list1):
    clean_str = ''.join([x for x in list1 if x.lower() not in volwes])
    print(clean_str)

1 Comment

The method with the remove function is really interesting!
2
def anti_vowel(text):
new=[]
vowels = ("aeiouAEIOU")
for i in text:
    if i not in vowels:
        new.append(i)
return ''.join(new)

i hope this helps..

Comments

2
def anti_vowel(text):
  new_text = ""
  for i in text:
    if i == 'a' or i == 'A':
      pass
    elif i == 'e' or i == 'E':
      pass
    elif i == 'I' or i == 'i':
      pass
    elif i == 'o' or i == 'O':
      pass
    elif i == 'u' or i == 'U':
      pass
    else:
      new_text = new_text + i
  return new_text

print anti_vowel('Hey look Words!')

Comments

1

My implementation:


# Ask the user for input:
user_input = input("enter a string with some vowels: ")
print("input string: " + str(user_input))
vowels = ('a','e','i','o','u','A','E','I','O','U')
new_string="";
for i in range(0,len(user_input),1):
    if user_input[i] in vowels:
        print ('found a vowel, removing...')
    else:
        new_string+=user_input[i]
print("I've removed the vowels for you. You're welcome! The new string is: " + new_string)

Comments

1

A fairly simple approach could be;

def anti_vowel(text):
    t = ''
    for c in text:
        if c in "aeiouAEIOU":
            pass
    else:  
        t += c  
    return t  

Comments

1
def anti_vowel(text):
    t=""
    for c in text:
        for i in "ieaouIEAOU":
            if c==i:
                c=""
            else:
                c=c
        t=t+c
    return t

1 Comment

Welcome to Stack Overflow! Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.