从 Python 中的字符串中删除元音的正确代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/21581824/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct code to remove the vowels from a string in Python
提问by KRS-fun
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".
输入anti_vowel("Hey look words")--> 输出:"Hey lk wrds".
Apparently it's not working on the 'e', can anyone explain why?
显然它不适用于'e',谁能解释为什么?
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
采纳答案by Grijesh Chauhan
The function str.replace(old, new[, max])don't changes cstring itself (wrt to cyou calls) just returns a new string which the occurrences of old have been replaced with new. So newstrjust contains a string replaced by last vowel in cstring that is the oand hence you are getting "Hey lk wrds"that is same as "Hey look words".replace('o', ''). 
该函数str.replace(old, new[, max])不会更改c字符串本身(向c您调用)只返回一个新字符串,其中旧的出现已被新替换。所以newstr只包含一个由字符串中的最后一个元音替换的c字符串,即o,因此您得到的字符串"Hey lk wrds"与"Hey look words".replace('o', '').
I think you can simply write anti_vowel(c)as: 
我认为你可以简单地写成anti_vowel(c):
''.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.
我正在做的是遍历字符串,如果一个字母不是元音,那么只将它包含在列表(过滤器)中。过滤后,我将列表作为字符串加入。
回答by gravetii
You should do this:
你应该做这个:
initialize newstrto c, and then
初始化newstr为c,然后
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:
那是因为str.replace(old, new[, max])在替换字符后返回字符串的副本:
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.
方法 replace() 返回字符串的副本,其中 old 的出现已被 new 替换,可选择将替换次数限制为最大值。
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:
你也可以用更pythonic的方式来做:
''.join([x for x in c if x not in vowels])
回答by Laur Ivan
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.
如果您经常使用该函数,则可以编译正则表达式并使用编译版本。
回答by CuriousCase
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
回答by Plaisance
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")
回答by Liyan Chang
Try String.translate.
试试 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.
string.translate(s, table[, deletechars])
从 s 中删除 deletechars 中的所有字符(如果存在),然后使用 table 转换字符,它必须是一个 256 字符的字符串,给出每个字符值的转换,按其序数索引。如果 table 为 None,则仅执行字符删除步骤。
https://docs.python.org/2/library/string.html#string.Template.substitute
https://docs.python.org/2/library/string.html#string.Template.substitute
Or if you're using the newfangled Python 3:
或者,如果您使用的是新奇的 Python 3:
>>> table = str.maketrans(dict.fromkeys('aeiouAEIOU'))
>>> "Hey look words.translate(table)
'Hy lk wrds'
回答by user5532093
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
回答by niksy
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..
我希望这有帮助..
回答by Ahsan Salem
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:
我知道关于这个问题有很多正确的解决方案,但我想添加一些解决这个问题的有趣方法。如果您来自 C++/C# 或 Java,您将倾向于使用类似 compare then 的操作使用索引来删除 for 循环中不需要的条目。Python 具有 Remove 和 Del 函数。remove 函数使用值,del 使用索引。pythonic 解决方案在最后一个函数中。让我们看看我们如何做到这一点:
Here we are using the index in a for loop and del function very similar in C++:
这里我们在 for 循环和 del 函数中使用索引,在 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:
你应该如何在python中做到这一点?使用列表理解!它很美:
def remove_vol(list1):
    clean_str = ''.join([x for x in list1 if x.lower() not in volwes])
    print(clean_str)
回答by Idodo
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)

