将isalpha()和isspace()合并为1个statemen

2024-09-27 00:14:29 发布

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

我正在寻找一个函数,它将方法isalpha()isspace()组合成一个方法。 我想检查给定的字符串是否只包含字母和/或空格,例如:

"This is text".isalpha_or_space()
# True

但是,通过这两种方法,我得到:

"This is text".isalpha() or "This is text".isspace()
# False

因为字符串不仅是alpha,也不是空格。你知道吗


当然,我可以迭代每个字符并检查它的空格或alpha。你知道吗

我还可以将字符串与("abcdefghijklmnopqrstuvwxyz" + " ")进行比较

然而,这两种方法在我看来都不太像Python——让我相信不是这样。你知道吗


Tags: or方法函数字符串textalphafalsetrue
3条回答

最具python风格的是使用def来表示:

def isalpha_or_space(self):
    if self == "":
        return False
    for char in self:
        if not (char.isalpha() or char.isspace()):
            return False
    return True

把它作为方法贡献给str并不容易,因为Python不鼓励对内置类型进行monkeypatching。我的建议是把它作为一个模块级函数。你知道吗

尽管如此,仍然可以模拟方法的接口,因为Python中的大多数名称空间都是可写的,如果您知道在哪里可以找到它们的话。下面的建议不是Pythonic,而是依赖于实现细节。你知道吗

>>> import gc
>>> def monkeypatch(type_, func): 
...     gc.get_referents(type_.__dict__)[0][func.__name__] = func 
...
>>> monkeypatch(str, isalpha_or_space)
>>> "hello world".isalpha_or_space()
True

您可以使用以下解决方案:

s != '' and all(c.isalpha() or c.isspace() for c in s)

使用regular expression (regex)

>>> import re
>>> result = re.match('[a-zA-Z\s]+$', "This is text")
>>> bool(result)
True

分解:

  • ^{}-Python的regex模块
  • [a-zA-Z\s]-任何字母或空格
  • +-上一项的一个或多个
  • $-字符串结尾

以上代码适用于ASCII字母。对于Python 3上的整个Unicode范围,不幸的是正则表达式有点复杂:

>>> result = re.match('([^\W\d_]|\s)+$', 'un café')

分解:

  • (x|y)-xy
  • [^\W\d_]-除了数字或下划线之外的任何word character

Mark TolonenanswerHow to match all unicode alphabetic characters and spaces in a regex?

相关问题 更多 >

    热门问题