从字符串Python中删除字符

从字符串Python中删除字符,python,string,Python,String,我正在尝试编写一个函数来去除给定字符串中的元音,但它的行为似乎不符合它应该做的 def anti_vowel(text): for c in text: if c in "aeiouAEIOU": no_vowel = text.replace(c, '') return no_vowel print(anti_vowel('Hello World') 因此,与其打印 Hll Wrld 它打印 Hell Wrld (提前)感谢您的

我正在尝试编写一个函数来去除给定字符串中的元音,但它的行为似乎不符合它应该做的

def anti_vowel(text):
    for c in text:
        if c in "aeiouAEIOU":
            no_vowel = text.replace(c, '')
    return no_vowel
print(anti_vowel('Hello World')
因此,与其打印

Hll Wrld
它打印

Hell Wrld  

(提前)感谢您的帮助。

问题在于,
无元音
仅具有上次执行
text.replace(c.)
时的值。另一个问题是,
no_元音
只有在实际存在要删除的元音时才获取一个值;在
反元音('vwlss')
上,代码将失败。此外,在调用
str.replace()
之前,不必检查文本中是否包含字符

这应该起作用:

def anti_vowel(text):
    for vowel in "aeiouAEIOU":
        text = text.replace(vowel, '')
    return text
print(anti_vowel('Hello World'))
正如其他人所指出的,另一种方法是以不同的方式编写代码:

def anti_vowel(text):
    ''.join(c for c in text if c not in 'aeiouAEIOU')

请在
''.join()
中使用生成器表达式,而不是列表;这样的列表理解会不必要地分配内存。

您的代码不起作用,因为每次迭代您都会对文本重新分配
无元音
,并且您重复文本的字母,因为
替换
已经这样做了。你应该这样写:

def anti_vowel(text):
    no_vowel = text
    for c in 'aeiouAEIOU':
        no_vowel = no_vowel.replace(c, '')

    return no_vowel
或者,您可以使用列表理解。更具Python风格,运行速度更快:

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

您可以为此使用
string.translate()
。例如:

def anti_vowel(text):
  return text.translate(None, "aeiouAEIOU")

print(anti_vowel("hello world"))
在Python3中,
delete
参数不存在了,但是您仍然可以通过将字符映射到
None
来实现

def anti_vowel_py3(text):
   return text.translate({ord(i): None for i in "aeiouAEIOU"})

print(anti_vowel_py3("hello world"))

在循环的每次迭代中,文本是“Hello World”,文本的最后一个元音是“o”,因此在循环的末尾,没有任何_元音是“Hell Wrld”

在python2.7中,改用方法translate。以下是官方文件:

翻译(…)

“Hello World”。translate(无,“aeiouAEIOU”)
给出正确的结果
“Hll Wrld”


另外,
re.sub(“[aeiouAEIOU]”,“,”Hello World“)
适用于python2.7和python3

哪里定义了
no_元音
?这不起作用,它返回
“['H','l','W','r','l','d']”
。这是:
'.join(如果c不在'aeiouAEIOU'中,则文本中的c代表c)
您需要关闭该字符串。@leaf因为
str.join
需要一个序列(而不是生成器),所以在将其转换为列表时,使用生成器只会增加不必要的开销。@MSeifert也许您是正确的,但我仍然不能真正理解使用生成器的效率有多低。@leaf只有在不需要所有元素或随机访问的情况下,生成器才有用。您可以查看源代码()和文档()。在这种情况下,这相当于
list(generator)
,这显然比理解列表要慢。回答得好,但最后一句话不是真的。使用
str.join
时,请始终使用列表理解。
join
的参数将始终转换为一个序列,因此生成器表达式的速度较慢,并且与列表理解一样节省内存。@MSeifert您有支持该声明的引用吗?该引用是
str.join
的python源代码:,另请参见我的另一个“是”,即“仅”显示它已转换为序列。生成器不是序列,将生成器转换为序列比一开始创建序列要慢得多。这不起作用,会导致
TypeError
:translate()只接受一个参数(给定2个)。@Sybren这在Python2.7中有效,但在python3中有效,方法
translate
的参数
deletechars
已不存在。@Sybren
re.sub(“[aeiouAEIOU]”、“,“Hello World”)
将同时适用于python2.7和python3
 S.translate(table [,deletechars]) -> string

 Return a copy of the string S, where all characters occurring
 in the optional argument deletechars are removed, and the
 remaining characters have been mapped through the given
 translation table, which must be a string of length 256 or None.

 If the table argument is None, no translation is applied and
 the operation simply removes the characters in deletechars.