help please
help please

Reputation: 115

How can I tell if a string only contains letter AND spaces

I'm having trouble figuring out the above question and have a felling I should be testing every character with "for character in string" however I cant really figure out how that would work

This is what I have now but I know it doesnt work as intended because it only allows me to test letters but I also need to know spaces so for example " MY dear aunt sally" should say yes contains only letters and spaces

    #Find if string only contains letters and spaces
    if string.isalpha():
      print("Only alphabetic letters and spaces: yes")
    else:
      print("Only alphabetic letters and spaces: no")

Upvotes: 4

Views: 4180

Answers (4)

Avinash Raj
Avinash Raj

Reputation: 174696

The below re.match fucntion would return a match object only if the input contain alphabets or spaces.

>>> re.match(r'[A-Za-z ]+$', 'test string')
<_sre.SRE_Match object; span=(0, 11), match='test string'>
>>> re.match(r'(?=.*? )[A-Za-z ]+$', 'test@bar')
>>> 

Upvotes: 0

Hackaholic
Hackaholic

Reputation: 19733

just another way for Fun, I know its not that good:

>>> a
'hello baby'
>>> b
'hello1 baby'
>>> re.findall("[a-zA-Z ]",a)==list(a)  # return True if string is only alpha and space
True
>>> re.findall("[a-zA-Z ]",b)==list(b) # returns False
False

Upvotes: 1

Shashank
Shashank

Reputation: 13869

Cascade replace with isalpha:

'a b'.replace(' ', '').isalpha() # True

replace returns a copy of the original string with everything but the spaces. Then you can use isalpha on that return value (since the return value is a string itself) to test if it only contains alphabet characters.

To match all whitespace, you're probably going to want to use Kasra's answer, but just for completeness, I'll demonstrate using re.sub with a whitespace character class:

import re
re.sub(r'\s', '', 'a b').isalpha()

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107287

You can use a generator expression within all built-in function :

if all(i.isalpha() or i.isspace() for i in my_string)

But note that i.isspace() will check if the character is a whitespace if you just want space you can directly compare with space :

if all(i.isalpha() or i==' ' for i in my_string)

Demo:

>>> all(i.isalpha() or i==' ' for i in 'test string')
True
>>> all(i.isalpha() or i==' ' for i in 'test    string') #delimiter is tab
False
>>> all(i.isalpha() or i==' ' for i in 'test#string')
False
>>> all(i.isalpha() or i.isspace() for i in 'test string')
True
>>> all(i.isalpha() or i.isspace() for i in 'test       string')
True
>>> all(i.isalpha() or i.isspace() for i in 'test@string')
False

Upvotes: 5

Related Questions