Posts

Showing posts with the label Contain

Checking If String Is Only Letters And Spaces - Python

Answer : 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)): ...