在 Python 中,从字符串中删除元音的正确代码

2025-03-04 08:27:00
admin
原创
76
摘要:问题描述:我很确定我的代码是正确的,但它似乎没有返回预期的输出:输入anti_vowel("Hey look words") -->输出:"Hey lk wrds"。显然它不起作用'e',有人能解释一下为什么吗?def anti_vowel(c): new...

问题描述:

我很确定我的代码是正确的,但它似乎没有返回预期的输出:

输入anti_vowel("Hey look words") -->输出:"Hey lk wrds"

显然它不起作用'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

解决方案 1:

该函数str.replace(old, new[, max])不会改变c字符串本身(就c您调用的而言)。它只是返回一个新字符串,其中的old已被 替换new。因此,它只包含一个由字符串newstr中最后一个元音替换的字符串,即 ,因此您得到的,与 相同。c`o"Hey lk wrds""Hey look words".replace('o', '')`

我认为你可以简单地写成anti_vowel(c)

''.join([l for l in c if l not in vowels]);

我所做的是遍历字符串,如果某个字母不是元音,则仅将其包含进去list(filters)。 过滤后,我将列表重新合并为一个字符串。

解决方案 2:

为什么不使用正则表达式来做呢?根据文档,类似下面的方法应该可行:

import re

def anti_vowel(s):
    result = re.sub(r'[AEIOU]', '', s, flags=re.IGNORECASE)
    return result

如果您经常使用该函数,您可以编译正则表达式并使用编译后的版本。

解决方案 3:

尝试 String.translate。

>>> "Hey look words".translate(None, 'aeiouAEIOU')
'Hy lk wrds'

字符串.翻译(s,表[,deletechars])

从 s 中删除 deletechars 中的所有字符(如果存在),然后使用 table 翻译这些字符,table 必须是一个 256 个字符的字符串,为每个字符值提供翻译,按其序数索引。如果 table 为 None,则只执行字符删除步骤。

https://docs.python.org/2/library/string.html#string.Template.substitute

或者如果你正在使用新潮的 Python 3:

>>> table = str.maketrans(dict.fromkeys('aeiouAEIOU'))
>>> "Hey look words".translate(table)
'Hy lk wrds'

解决方案 4:

另一种选择是放弃元音变量并将要删除的字符放入循环中。

    def anti_vowel(text):
        for i in "aeiouAEIOU":
            text = text.replace(i,"")
        return text

    print anti_vowel("HappIEAOy")

解决方案 5:

你应该这样做:

初始化newstrc,然后

for x in c.lower():
    if x in vowels:
        newstr = newstr.replace(x, "")

这是因为str.replace(old, new[, max])返回的是替换字符后的字符串副本:

方法 replace() 返回字符串的副本,其中出现的 old 已被 new 替换,可选择将替换次数限制为最大。

因此,这是正确的代码:

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

您还可以采用更 Python 的方式来完成此操作:

''.join([x for x in c if x not in vowels])

解决方案 6:

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

解决方案 7:

另一种更简单的方法是从字符串中提取非元音字符并返回它们。

def anti_vowel(text):
    newstring=""
    for i in text:
        if i not in "aeiouAEIOU":
            newstring=newstring+i
    text=newstring
    return text

解决方案 8:

我知道这个问题有很多正确的解决方案,但我想添加一些有趣的方法来解决这个问题。如果你来自 C++/C# 或 Java,你会倾向于使用类似比较然后使用索引的操作来删除 for 循环中不需要的条目。Python 有 Remove 和 Del 函数。Remove 函数使用值,del 使用索引。Pythonic 解决方案在最后一个函数中。让我们看看我们如何做到这一点:

这里我们在 for 循环中使用索引,与 C++ 中的 del 函数非常相似:

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)

使用删除功能:

def remove_vol(str1): 
      list1 = list(str1)
      list2 = list(str1)
      for i in list1:
          if i in volwes:
              list2.remove(i)
      print(list2)

使用索引构建不包含不需要的字符的新字符串:

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)

与上面的解决方案相同,但使用的值:

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)

你应该如何在 Python 中做到这一点?使用列表推导!它很漂亮:

def remove_vol(list1):
    clean_str = ''.join([x for x in list1 if x.lower() not in volwes])
    print(clean_str)

解决方案 9:

def anti_vowel(text):
new=[]
vowels = ("aeiouAEIOU")
for i in text:
    if i not in vowels:
        new.append(i)
return ''.join(new)

我希望这有帮助。

解决方案 10:

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!')

解决方案 11:

我的实现:


# 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)

解决方案 12:

一个相当简单的方法可能是;

def anti_vowel(text):
    t = ''
    for c in text:
        if c in "aeiouAEIOU":
            pass
    else:  
        t += c  
    return t  

解决方案 13:

def anti_vowel(text):
    t=""
    for c in text:
        for i in "ieaouIEAOU":
            if c==i:
                c=""
            else:
                c=c
        t=t+c
    return t
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   4046  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   2770  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Freshdesk、ClickUp、nTask、Hubstaff、Plutio、Productive、Targa、Bonsai、Wrike。在当今快速变化的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多企业在项目管理过程中面临着诸多痛点,如任务分配不...
项目管理系统   90  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Monday、TeamGantt、Filestage、Chanty、Visor、Smartsheet、Productive、Quire、Planview。在当今快速变化的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多项目经理和团队在管理复杂项目时,常...
开源项目管理工具   105  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Smartsheet、GanttPRO、Backlog、Visor、ResourceGuru、Productive、Xebrio、Hive、Quire。在当今快节奏的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多企业在选择项目管理工具时常常面临困惑:...
项目管理系统   93  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用