Python:只保留字符串中的字母

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34214139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:37:17  来源:igfitidea点击:

Python: keep only letters in string

pythonpython-2.7

提问by

What is the best way to remove all characters from a string that are not in the alphabet? I mean, remove all spaces, interpunction, brackets, numbers, mathematical operators..

从字符串中删除不在字母表中的所有字符的最佳方法是什么?我的意思是,删除所有空格、标点符号、括号、数字、数学运算符..

For example:

例如:

input: 'as32{ vd"s k!+'
output: 'asvdsk'

回答by timgeb

You could use re, but you don't really need to.

你可以使用re,但你真的不需要。

>>> s = 'as32{ vd"s k!+'
>>> ''.join(x for x in s if x.isalpha())
'asvdsk'    
>>> filter(str.isalpha, s) # works in python-2.7
'asvdsk'
>>> ''.join(filter(str.isalpha, s)) # works in python3
'asvdsk'

回答by nehem

If you want to use regular expression, This should be quicker

如果你想使用正则表达式,这应该更快

import re
s = 'as32{ vd"s k!+'
print re.sub('[^a-zA-Z]+', '', s)

prints 'asvdsk'

印刷 'asvdsk'

回答by Patrick Yu

Here is a method that uses ASCII ranges to check whether an character is in the upper/lower case alphabet (and appends it to a string if it is):

这是一种使用 ASCII 范围检查字符是否在大写/小写字母表中的方法(如果是,则将其附加到字符串中):

s = 'as32{ vd"s k!+'
sfiltered = ''

for char in s:
    if((ord(char) >= 97 and ord(char) <= 122) or (ord(char) >= 65 and ord(char) <= 90)):
        sfiltered += char

The variable sfilteredwill show the result, which is 'asvdsk'as expected.

该变量sfiltered将显示结果,'asvdsk'正如预期的那样。