Correct code to remove the vowels from a string in Python

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The function str.replace(old, new[, max]) don’t changes c string itself (wrt to c you calls) just returns a new string 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" that 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 back list as a string.

Method 2

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.

Method 3

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'

Method 4

Another option is to forego the vowel variable and put the char’s to remove in the loop.

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

    print anti_vowel("HappIEAOy")

Method 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])

Method 6

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

Method 7

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

Method 8

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)

Method 9

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..

Method 10

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!')

Method 11

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)

Method 12

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

Method 13

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x