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

2024-06-26 13:43:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

比如:

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

Tags: 函数字符串infalsetruereturnifdef
2条回答

使用^{} method;如果字符串中的所有字符都是字母,则它只返回True。用not对结果求反;如果object.isalpha()返回True(字符串中只有个字母),则not object.isalpha()返回{},反之亦然:

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

演示:

^{pr2}$

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

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使用一个生成器表达式来计算字符串s中的所有字符{}。在

但是,鉴于str.isalpha已经存在,这是在重新设计轮子。在

相关问题 更多 >