sithlorddahlia
sithlorddahlia

Reputation: 167

Checking if string is only letters and spaces - Python

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?

Upvotes: 15

Views: 47842

Answers (9)

Galih Wicakso
Galih Wicakso

Reputation: 43

You can use regex for doing that action

import re


name = input('What is your name ?')

if not re.match("^[a-z A-Z]*$", name):
    print("Only Alphabet and Space are allowed")
else:
    print("Hello" ,name)

Upvotes: 1

IlayG01
IlayG01

Reputation: 108

the usage of isalpha() is less specific than using regex.

isalpha will return true not only for [a-zA-Z] but for other alphabetic unicodes.

use bool(re.match('^[a-zA-Z\s]+$', name)

Upvotes: 0

Misterlen
Misterlen

Reputation: 61

use a pattern match like this

import re
alpha_regex = "^[a-z A-Z]+$"
if re.match(alpha_regex, string):
   print("Only alphabetical letters and spaces: yes")
else:
   print("Only alphabetical letters and spaces: no")

Upvotes: 0

Daniel Garcia
Daniel Garcia

Reputation: 29

// remove spaces and question is only alphanumeric
def isAlNumAndSpaces(string):
    return string.replace(" ","").isalnum()
strTest = input("Test a string: ")
if isAlNumAndSpaces(strTest):
    print("Only alphabetical letters and spaces: yes")
else:
    print("Only alphabetical letters and spaces: no")

Upvotes: 0

vikash chand singh
vikash chand singh

Reputation: 21

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

Upvotes: 2

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

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.

Upvotes: 2

flaschbier
flaschbier

Reputation: 4177

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?

Upvotes: 3

anon
anon

Reputation:

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

Upvotes: 3

rob mayoff
rob mayoff

Reputation: 385540

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

Upvotes: 26

Related Questions