繁体   English   中英

有没有办法在Python中删除字符串中除字母之外的所有字符?

[英]Is there a way to remove all characters except letters in a string in Python?

我调用了一个函数,该函数返回包含从 ( 到 "、以及 和数字的各种字符的代码。

有没有一种优雅的方法来删除所有这些,所以我最终只有字母?

给定的

s = '@#24A-09=wes()&8973o**_##me'  # contains letters 'Awesome'    

您可以使用生成器表达式过滤掉非字母字符:

result = ''.join(c for c in s if c.isalpha())

或者用filter

result = ''.join(filter(str.isalpha, s))    

或者您可以使用re.sub用空格替换非 alpha :

import re
result = re.sub(r'[^A-Za-z]', '', s)

使用 RegEx 的解决方案在这里非常简单:

import re
newstring = re.sub(r"[^a-zA-Z]+", "", string)

其中string是您的字符串,而newstring是没有非字母字符的字符串。 这样做是用空字符串替换每个不是字母的字符,从而将其删除。 但是请注意,这里的 RegEx 可能有点矫枉过正。

更实用的方法是:

newstring = "".join(filter(str.isalpha, string))

不幸的是,您不能只是在filter对象上调用str将其转换为字符串,那看起来会好得多......
以 Pythonic 的方式走下去

newstring = "".join(c for c in string if c.isalpha())

你没有提到你只想要英文字母,这是一个国际解决方案:

import unicodedata

str = u"hello, ѱϘяԼϷ!"
print ''.join(c for c in str if unicodedata.category(c).startswith('L'))

这是另一个,使用string.ascii_letters

>>> import string
>>> "".join(x for x in s if x in string.ascii_letters)

`

>>> import re
>>> string = "';''';;';1123123!@#!@#!#!$!sd         sds2312313~~\"~s__"
>>> re.sub("[\W\d_]", "", string)
'sdsdss'
s = '@#24A-09=wes()&8973o**_##me'

print(filter(str.isalpha, s))

# Awesome

关于filter返回值:

filter(function or None, sequence) -> list, tuple, or string

嗯,我在这种情况下为自己使用这个

对不起,如果它已经过时了:)

string = "The quick brown fox jumps over the lazy dog!"
alphabet = "abcdefghijklmnopqrstuvwxyz"

def letters_only(source):
    result = ""
    for i in source.lower():
        if i in alphabet:
            result += i
    return result

print(letters_only(string))

暂无
暂无

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

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