我正在寻找一个函数,它将方法isalpha()
和isspace()
组合成一个方法。
我想检查给定的字符串是否只包含字母和/或空格,例如:
"This is text".isalpha_or_space()
# True
但是,通过这两种方法,我得到:
"This is text".isalpha() or "This is text".isspace()
# False
因为字符串不仅是alpha,也不是空格。你知道吗
当然,我可以迭代每个字符并检查它的空格或alpha。你知道吗
我还可以将字符串与("abcdefghijklmnopqrstuvwxyz" + " ")
进行比较
然而,这两种方法在我看来都不太像Python——让我相信不是这样。你知道吗
最具python风格的是使用
def
来表示:把它作为方法贡献给
str
并不容易,因为Python不鼓励对内置类型进行monkeypatching。我的建议是把它作为一个模块级函数。你知道吗尽管如此,仍然可以模拟方法的接口,因为Python中的大多数名称空间都是可写的,如果您知道在哪里可以找到它们的话。下面的建议不是Pythonic,而是依赖于实现细节。你知道吗
您可以使用以下解决方案:
使用regular expression (regex):
分解:
[a-zA-Z\s]
-任何字母或空格+
-上一项的一个或多个$
-字符串结尾以上代码适用于ASCII字母。对于Python 3上的整个Unicode范围,不幸的是正则表达式有点复杂:
分解:
(x|y)
-x或y[^\W\d_]
-除了数字或下划线之外的任何word character从Mark Tolonen的answer到How to match all unicode alphabetic characters and spaces in a regex?
相关问题 更多 >
编程相关推荐