简体   繁体   English

在python中删除字符串中的元音:

[英]Deleting vowels in string in python:

The code: 编码:

def anti_vowel(text):
    string1 = list(text)
    for i in string1:
        if i=='A'or i=='a' or i=='E'or i=='e'or i=='O'or i=='o' or \
        i=='I'or i=='i' or i=='U' or i=='u':
            del(string1[string1.index(i)])
    string2 = ''.join(string1)
    return string2

Gives an error: 给出一个错误:

Your function fails on anti_vowel("Hey look Words!"). 您的函数在anti_vowel上失败(“嗨,看字!”)。

It returns "Hy lk Words!" 它返回“ Hy lk Words!” when it should return "Hy lk Wrds!". 何时应返回“ Hy lk Wrds!”。

I don't know how to delete that "o" in "words". 我不知道如何删除“单词”中的“ o”。 Can you tell me what's wrong? 你能告诉我怎么了吗?

This looks like a good place to be using regular expressions... 这看起来像是使用正则表达式的好地方...

import re
re_vowels = re.compile(r'[AaEeIiOoUu]')
def anti_vowel(text):
    return re_vowels.sub('', text)

Results in 'hy lk Wrds!' 结果为'hy lk Wrds!'

But if you have to fix the code you have, try this... 但是,如果您必须修复自己的代码,请尝试此...

def anti_vowel(text):
    string1 = list(text)
    for c in xrange(len(string1)-1,-1,-1):
        i = string1[c]
        if i=='A'or i=='a' or i=='E'or i=='e'or i=='O'or i=='o' or \
        i=='I'or i=='i' or i=='U' or i=='u':
            del(string1[c])
    string2 = ''.join(string1)
    return string2

Or... 要么...

def anti_vowel(text):
    return ''.join([c for c in text if c.lower() not in 'aeiou'])

In your code you are trying to delete something that doesn't exist anymore. 在您的代码中,您尝试删除不再存在的内容。 If you are going to iterate through a list while deleting elements, iterate through it in reverse order (or use list comprehensions). 如果要在删除元素的同时遍历列表,请以相反的顺序进行遍历(或使用列表推导)。

If you just want to remove vowels from strings this is an easy way to do it: 如果您只想从字符串中删除元音,这是一种简单的方法:

word = "hello world"
w = filter(lambda x: x not in 'aeiouAEIOU', word)
print w

Output: 输出:

hll wrld

your code is messy and not nice you can do it a easy way by setting vowels and comparing them to the value like below. 您的代码混乱且不好,您可以通过设置元音并将其与下面的值进行比较来轻松实现。 This then will do a replace on the vowels which match in the string. 然后,这将对字符串中匹配的元音进行替换。

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

        return string1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM