Correct code to remove the vowels from a string in

2019-01-02 21:37发布

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

标签: python
13条回答
浅入江南
2楼-- · 2019-01-02 21:55

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])
查看更多
刘海飞了
3楼-- · 2019-01-02 21:55

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)
查看更多
笑指拈花
4楼-- · 2019-01-02 21:57
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!')
查看更多
伤终究还是伤i
5楼-- · 2019-01-02 21:58

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")
查看更多
妖精总统
6楼-- · 2019-01-02 22:02

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)
查看更多
妖精总统
7楼-- · 2019-01-02 22:07

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.

查看更多
登录 后发表回答