How to determine if a string contains only AND letters

I'm having trouble figuring out the above question, and I have felling. I have to test each character with "for character in line", however I cannot figure out how this will work

This is what I have now, but I know that it does not work properly, because it allows me to check letters, but I also need to know the spaces, for example, 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")
+4
source share
4 answers

You can use the generator expression in the allbuilt-in function:

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

, i.isspace() , , space, :

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

:

>>> 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
+5

, , :

>>> 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
+1

replace isalpha:

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

replace , . isalpha ( ), , .

, , , Kasra, , re.sub :

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

re.match fucntion , .

>>> 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')
>>> 
0

All Articles