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

sit*_*lia 6 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")
Run Code Online (Sandbox Code Playgroud)

我一直在尝试please,它出现了,因为Only alphabetical letters and spaces: no我用or而不是and,但只满足一个条件.我需要满足两个条件.那句话必须包含字母空格,但必须至少包含一种.它不得包含任何数字.

我在这里错过了什么让python返回字母和空格只包含在字符串中?

rob*_*off 14

角色不能同时是角色空间.它可以是alpha 空格.

要求字符串仅包含alpha和空格:

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")
Run Code Online (Sandbox Code Playgroud)

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

if any(x.isalpha() for x in string) and any(x.isspace() for x in string):
Run Code Online (Sandbox Code Playgroud)

要求字符串包含至少一个alpha,至少一个空格,以及仅包含alpha和空格:

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)):
Run Code Online (Sandbox Code Playgroud)

测试:

>>> 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
Run Code Online (Sandbox Code Playgroud)