简体   繁体   English

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

[英]Detecting whether a string contains non-letters

How can I write a function that detects whether a string has non-letter characters in it? 如何编写一个检测字符串中是否包含非字母字符的函数?

Something like: 就像是:

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

Use the str.isalpha() method ; 使用str.isalpha()方法 it only returns True if all characters in a string are letters. 如果字符串中的所有字符均为字母,则仅返回True Negate the result with not ; not结果; if object.isalpha() returns True ( only letters in the string) then not object.isalpha() returns False , and vice versa: 如果object.isalpha()返回True字符串中的字母),则not object.isalpha()返回False ,反之亦然:

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

Demo: 演示:

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

The approach your pseudocode attempts could be written as follows: 伪代码尝试的方法可以编写为:

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)

This uses string.ascii_letters to define valid characters (rather than write out your own string literal), a set to provide efficient ( O(1) ) membership testing and all with a generator expression to evaluate all characters c in the string s . 它使用string.ascii_letters定义有效字符(而不是写出自己的字符串文字),用于提供有效( O(1) )成员资格测试的set ,以及all带有生成器表达式的表达式,用于评估字符串s中的所有字符c

Given that str.isalpha already exists, though, this is reinventing the wheel. 但是,鉴于str.isalpha已经存在,这正在重新发明轮子。

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

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