Trying to get python to return that a string contains ONLY alphabetic letters AND spaces
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")
I've been trying please
and it comes up as Only alphabetical letters and spaces: no
I've used or
instead of and
, but that only satisfies one condition. I need both conditions satisfied. That is the sentence must contain only letters and only spaces but must have at least one of each kind. It must not contain any numerals.
What am I missing here for python to return both letters and spaces are only contained in the string?
A character cannot be both an alpha and a space. It can be an alpha or a space.
To require that the string contains only alphas and spaces:
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")
To require that the string contains at least one alpha and at least one space:
if any(x.isalpha() for x in string) and any(x.isspace() for x in string):
To require that the string contains at least one alpha, at least one space, and only alphas and spaces:
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)):
Test:
>>> 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