Checking if string is only letters and spaces - Python

拥有回忆 提交于 2019-12-07 03:54:02

问题


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?


回答1:


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



回答2:


The correct solution would use an or.

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")

Although you have a string, you are iterating over the letters of that string, so you have one letter at a time. So, a char alone cannot be an alphabetical character AND a space at the time, but it will just need to be one of the two to satisfy your constraint.

EDIT: I saw your comment in the other answer. alphabet = string.isalpha() return True, if and only if all characters in a string are alphabetical letters. This is not what you want, because you stated that you want your code to print yes when execute with the string please, which has a space. You need to check each letter on its own, not the whole string.

Just to convince you that the code is indeed correct (well, ok, you need to execute it yourself to be convinced, but anyway):

>>> string = "please "
>>> 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")


Only alphabetical letters and spaces: yes

EDIT 2: Judging from your new comments, you need something like this:

def hasSpaceAndAlpha(string):
    return any(char.isalpha() for char in string) and any(char.isspace() for char in string) and all(char.isalpha() or char.isspace() for char in string)

>>> hasSpaceAndAlpha("text# ")
False
>>> hasSpaceAndAlpha("text")
False
>>> hasSpaceAndAlpha("text ")
True

or

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

>>> hasSpaceAndAlpha("text# ")
Only alphabetical letters and spaces: no
>>> hasSpaceAndAlpha("text")
Only alphabetical letters and spaces: no
>>> hasSpaceAndAlpha("text ")
Only alphabetical letters and spaces: yes



回答3:


Actually, it is an pattern matching exercise, so why not use pattern matching?

import re
r = re.compile("^[a-zA-Z ]*$")
def test(s):
    return not r.match(s) is None  

Or is there any requirement to use any() in the solution?




回答4:


You need any if you want at least one of each in the string:

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

If you want at least one of each but no other characters you can combine all,any and str.translate , the following will only return True if we have at least one space, one alpha and contain only those characters.

 from string import ascii_letters

 s = input("Enter a string: ")

 tbl = {ord(x):"" for x in ascii_letters + " "}

if all((any(x.isalpha() for x in s),
   any(x.isspace() for x in s),
   not s.translate(tbl))):
    print("all good")

Check if there is at least one of each with any then translate the string, if the string is empty there are only alpha characters and spaces. This will work for upper and lowercase.

You can condense the code to a single if/and:

from string import ascii_letters

s = input("Enter a string: ")
s_t = s.translate({ord(x):"" for x in ascii_letters})

if len(s_t) < len(s) and s_t.isspace():
    print("all good")

If the length of the translated string is < original and all that is left are spaces we have met the requirement.

Or reverse the logic and translate the spaces and check if we have only alpha left:

s_t = s.translate({ord(" "):"" })
if len(s_t) < len(s) and s_t.isalpha():
    print("all good")

Presuming the string will always have more alphas than spaces, the last solution should be by far the most efficient.




回答5:


    string = input("Enter a string: ")
    st1=string.replace(" ","").isalpha()
    if (st1):
        print("Only alphabetical letters and spaces: yes")
    else:
        print("Only alphabetical letters and spaces: no")


来源:https://stackoverflow.com/questions/29460405/checking-if-string-is-only-letters-and-spaces-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!