python - 检查字符串是否只是字母和空格 - Python

标签 python contain

试图让 python 返回一个字符串只包含字母和空格

string = input("Enter a string: ")

if all(x.isalpha() and x.isspace() for x in string):
    print("Only alphabetical letters and spaces: yes")
else:
    print("Only alphabetical letters and spaces: no")

我一直在尝试 please 结果是 Only alphabetical letters and spaces: no 我用 or 而不是 and,但那只满足一个条件。我需要满足这两个条件。也就是说,句子必须包含仅字母仅包含空格,但必须至少包含一种。它必须包含任何数字。

对于 python 返回字母和空格只包含在字符串中,我在这里缺少什么?

最佳答案

一个字符不能既是字母又是空格。它可以是字母 空格。

要求字符串只包含字母和空格:

string = input("Enter a string: ")

if all(x.isalpha() or x.isspace() for x in string):
    print("Only alphabetical letters and spaces: yes")
else:
    print("Only alphabetical letters and spaces: no")

要求字符串至少包含一个字母和至少一个空格:

if any(x.isalpha() for x in string) and any(x.isspace() for x in string):

要求字符串至少包含一个字母,至少一个空格,并且只包含字母和空格:

if (any(x.isalpha() for x in string)
    and any(x.isspace() for x in string)
    and all(x.isalpha() or x.isspace() for x in string)):

测试:

>>> string = "PLEASE"
>>> if (any(x.isalpha() for x in string)
...     and any(x.isspace() for x in string)
...     and all(x.isalpha() or x.isspace() for x in string)):
...     print "match"
... else:
...     print "no match"
... 
no match
>>> string = "PLEASE "
>>> if (any(x.isalpha() for x in string)
...     and any(x.isspace() for x in string)
...     and all(x.isalpha() or x.isspace() for x in string)):
...     print "match"
... else:
...     print "no match"
... 
match

关于python - 检查字符串是否只是字母和空格 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29460405/

相关文章:

python - 在子线程中创建BeautifulSoup对象会打印编码错误

excel - 删除第一列以外的空白行

javascript - JS 检查页面/内容是否不包含

python - 使用 python 字典作为临时内存中键值数据库?

python - 将列表中的每三个项目组合在一起 - Python

python - DataFrame.write.parquet - HIVE 或 Impala 无法读取 Parquet 文件

javascript - 为什么我的元素不是 :contains(variable) work when using variable instead of string? jquery

python - 基于顶点名称 Python igraph 执行图的并集

jquery检查返回值是否包含字符串

Python pandas 检查单元格中列表的最后一个元素是否包含特定字符串