gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:21:54 24 4
gpt4 key购买 nike

试图让 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com