Skip to main content
 首页 » 编程设计

python之从python列表中过滤对象

2025年05月04日9thcjp

我正在尝试编写一些程序来过滤文本字符串中的所有元音,但我不确定为什么我的函数不起作用。这是我的代码

def anti_vowel(text): 
 letters = text.split() #make a list of all the letters in the string 
 index = 0 #for del 
 for x in letters: 
     if x == "a" or x == "A" or x == "u" or x == "U" or x == "i" or x == "I" or x == "o" or x == "O" or x == "e" or x == "E": 
         del letters[index] 
     index += 1 #to make the if-clause work 
 return "".join(letters) #turn the edited list into a string 

在遍历字母时,当字母中的对象是元音时,应该激活 if 子句,对吧?所以它应该删除那个对象。但是我做错了什么?

请您参考如下方法:

我会使用 re.sub

re.sub(r'(?i)[AEIOU]', '', st) 

解释:

  • (?i) 不区分大小写的修饰符有助于进行不区分大小写的匹配。
  • [AEIOU] 匹配给定列表中的任何一个字符。由于我们已经添加了不区分大小写的修饰符,因此这将同时匹配大写和小写元音。