I am writing a program, part of it requires the input of a name. The name can only be alpha and spaces (eg. John Smith) it cannot be John Smith1 If an invalid character IS
You can use the replace method of strings to get rid of white-spaces and then use the isalpha() method.
An example:
>>> def get_name():
... name = raw_input('name: ') # use a simple "input" in python3
... if not name.replace(' ', '').isalpha():
... print('Bad name!!!')
... else:
... print('Good name!')
...
>>> get_name()
name: My name
Good name!
>>> get_name()
name: Bad Nam3
Bad name!!!
>>> get_name()
name: Jon Skeet
Good name!
Note that this works also with non ascii-letters in python3:
#python3
>>> get_name()
name: Accented è
Good name!
>>> get_name()
name: Bad Nam3
Bad name!!!
Regular expressions are too complicated for this simple task.
Also because using [A-Za-z ]+ or similar wont match names with non ASCII letters.
And using \w includes digits.
If you don't want to match non-ASCII letters(such as 'è'), then you can try something like this:
>>> def get_name():
... name = raw_input('name: ') #input in python3
... try:
... name.encode('ascii')
... except UnicodeDecodeError:
... print('Bad name!!!')
... return
... if not name.replace(' ', '').isalpha():
... print('Bad name!!!')
... else:
... print('Good name!')
...
>>> get_name()
name: Accented è
Bad name!!!
>>> get_name()
name: The nam3
Bad name!!!
>>> get_name()
name: Guido Van Rossum
Good name!
Finally, an other way to check is this one:
>>> import string
>>> def good_name(name):
... return not set(name).difference(string.letters + ' ')
...
>>> good_name('Guivo Van Rossum')
True
>>> good_name('Bad Nam3')
False
And you can use it in this way:
name = raw_input('name: ') #input in python3
if good_name(name):
#stuff for valid names
else:
#stuff for invalid names