从字符串Python中删除字符

时间:2016-12-11 05:13:12

标签: 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  

感谢(提前)帮助

4 个答案:

答案 0 :(得分:8)

问题是no_vowel仅具有上次执行text.replace(c, '')的值。另一个问题是no_vowel只有在实际要删除的元音时才会获得值;代码在anti_vowel('vwllss')上失败。此外,在调用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()中使用生成器表达式,而不是列表理解;这样的列表理解会不必要地分配内存。

答案 1 :(得分:4)

您可以使用$CI = & get_instance(); echo $CI->nuts_lib->enc($_REQUEST['clid']); return; 。例如:

string.translate()

使用Python 3,def anti_vowel(text): return text.translate(None, "aeiouAEIOU") print(anti_vowel("hello world")) 参数消失了,但你仍然可以通过将一个字符映射到delete来实现。

None

答案 2 :(得分:1)

您的代码无效,因为您为no_vowel重新分配文本的每次迭代都会重复,并且您将文本字母重复,因为replace已经执行了此操作。你应该这样写:

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

    return no_vowel

或者,您可以使用列表理解。更多Pythonic和更快的运行:

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

答案 3 :(得分:0)

在循环的每次迭代中,文本都是“Hello World”,文本的最后一个元音是“o”,所以在循环结束时,no_vowel是“Hell Wrld”。

在python2.7中,请使用方法translate。这是官方文件:

  

翻译(...)

 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.

"Hello World".translate(None, "aeiouAEIOU")会提供正确的结果"Hll Wrld"

此外,re.sub('[aeiouAEIOU]', "", "Hello World")适用于python2.7和python3