简体   繁体   English

从字符串Python中删除字符

[英]Removing characters from string Python

I'm trying to write a function that gets rid of the vowels in a given string, but it seems to not behave the way it should do... 我正在尝试编写一个函数来摆脱给定字符串中的元音,但它似乎没有按照它应该做的方式行事......

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

so instead of printing 而不是打印

Hll Wrld

It prints 它打印

Hell Wrld  

Thanks (in advance) for helping 谢谢(提前)帮助

The problem is that no_vowel only has the value of the last time that text.replace(c, '') was executed. 问题是no_vowel只有上次执行text.replace(c, '') Another issue is that no_vowel only gets a value when there is actually a vowel to remove; 另一个问题是no_vowel只在实际要删除元音时获取值; the code would fail on anti_vowel('vwllss') . 代码将在anti_vowel('vwllss')上失败。 Furthermore, you don't have to check whether a character is contained in the text before calling str.replace() . 此外,在调用str.replace()之前,您不必检查文本中是否包含字符。

This should work: 这应该工作:

def anti_vowel(text):
    for vowel in "aeiouAEIOU":
        text = text.replace(vowel, '')
    return text
print(anti_vowel('Hello World'))

As others indicated, another approach would be to write code in a different way: 正如其他人指出的那样,另一种方法是以不同的方式编写代码:

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

Please do use a generator expression in ''.join() and not a list comprehension; 请在''.join()使用生成器表达式而不是列表''.join() ; such a list comprehension would allocate memory unnecessarily. 这样的列表理解会不必要地分配内存。

You can use string.translate() for this. 您可以使用string.translate() For example: 例如:

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

print(anti_vowel("hello world"))

With Python 3 the delete argument is gone, but you can still do it by mapping a character to None . 使用Python 3, delete参数已经消失,但您仍然可以通过将字符映射到None

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

print(anti_vowel_py3("hello world"))

Your code doesnt work because every iteration you assign no_vowel with the text all over again and you iterate the text's letters what you shouldnt because replace already does it. 你的代码不能正常工作,因为每次迭代你都会将no_vowel重新分配给文本而你会迭代文本的字母,因为replace已经完成了。 You should write it like that: 你应该这样写:

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

    return no_vowel

Or, you could use a list comprehension. 或者,您可以使用列表理解。 More Pythonic and faster to run: 更多Pythonic和更快的运行:

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

In every iteration of the loop, text is "Hello World", and the last vowel of text is "o", so at the end of the loop, no_vowel is "Hell Wrld". 在循环的每次迭代中,文本是“Hello World”,文本的最后一个元音是“o”,所以在循环结束时,no_vowel是“Hell Wrld”。

In python2.7, use method translate instead. 在python2.7中,使用方法translate。 Here is the official document: 这是官方文件:

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") gives the correct result "Hll Wrld" "Hello World".translate(None, "aeiouAEIOU")给出了正确的结果"Hll Wrld"

Also, re.sub('[aeiouAEIOU]', "", "Hello World") works for both python2.7 and python3 另外, re.sub('[aeiouAEIOU]', "", "Hello World")适用于python2.7和python3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM