我开始学习Python,并尝试创建一个从给定字符串中删除元音的函数。 这是我的代码:
def anti_vowel(text):
li = []
for l in text:
li.append(l)
while 'a' in li:
li.remove('a')
while 'A' in li:
li.remove('A')
while 'A' in li:
li.remove('e')
while 'e' in li:
li.remove('E')
while 'E' in li:
li.remove('i')
while 'i' in li:
li.remove('I')
while 'I' in li:
li.remove('o')
while 'o' in li:
li.remove('O')
while 'u' in li:
li.remove('u')
while 'U' in li:
li.remove('U')
return "".join(li)
当我尝试运行它时,出现“ list.remove(x):x不在列表中”错误。 我知道这里已经有人问过这个错误,但是在那些特定情况下我并没有真正得到答案。 感谢您的阅读,请提供帮助:)
答案 0 :(得分:1)
def anti_vowel(text):
li = ''
for l in text:
if l.lower() not in 'aeiou':
li+=l
return li
答案 1 :(得分:0)
您过于复杂了,只需使用生成器表达式:
def anti_vowel(text):
return "".join(x for x in text if x not in "AEIOUaeiou")
>>> anti_vowel("asldkfoihyoihbiw")
'sldkfhyhbw'
您还可以使用循环:
def anti_vowel(text):
li = []
for l in text:
if l not in "AEIOUaeiou":
li.append(li)
return "".join(li)
答案 2 :(得分:0)
您的while
语句中有一些不匹配的地方,例如:
while 'e' in li:
li.remove('E')
如果没有“ E”但有“ e”,则会引起问题。
您要么需要检查并确保它们是一致的。
或者您可以编写一个小的函数来处理每个元音:
def remove(letters, vowel):
while vowel in letters:
letters.remove(vowel)
然后您可以为每个元音调用它。
def anti_vowel(text):
li = []
for l in text:
li.append(l)
for vowel in ['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U']:
remove(li, vowel)
return "".join(li)
根据Netware的回答,一种更Python化的方式是使用列表推导器或生成器来提取所需的字母。我只是指出您的错误原因。
如果您发现自己重复很多次,然后复制/粘贴然后进行微调,则可以轻松错过一些需要微调的地方。 尝试将重复项更改为函数。