检测字符串是否包含非字母

时间:2014-10-12 09:12:42

标签: python string

如何编写一个函数来检测字符串中是否包含非字母字符?

类似的东西:

def detection(a):
    if !"qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM" in a:
        return True
    else:
        return False
print detection("blablabla.bla")

2 个答案:

答案 0 :(得分:3)

使用str.isalpha() method;如果字符串中的所有字符都是字母,则它只返回True。使用not取消结果;如果object.isalpha()返回True(字符串中仅 字母),则not object.isalpha()会返回False,反之亦然:

def detection(string):
    return not string.isalpha()

演示:

>>> def detection(string):
...     return not string.isalpha()
... 
>>> detection('jfiopafbjk')
False
>>> detection('42jfiopafbjk')
True
>>> detection('jfiopafbjk42')
True
>>> detection('jfiop42afbjk')
True

答案 1 :(得分:1)

您的伪代码尝试的方法可以写成如下:

from string import ascii_letters

def detection(s, valid=set(ascii_letters)):
    """Whether or not s contains only characters in valid."""
    return all(c in valid for c in s)

这使用string.ascii_letters来定义有效字符(而不是写出您自己的字符串文字),使用set来提供有效的(O(1))成员资格测试和all生成器表达式,用于计算字符串c中的所有字符s

鉴于str.isalpha已经存在,这将重新发明轮子。

相关问题