Reputation: 1021
I need my program to validate the user input. So far I have defined a range of 'validLetters' and 'validNumbers':
validLetters = ('abcdefghijklmnopqrstuvwxyz ')
validNumbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
However, it should then validate like this:
name = input("What is your name?\n").lower()
while name == "" or name in validNumbers:
name = input("What is your name?\n").lower()
strinput0 = name
char_only0 = ''
for char in strinput0:
if char in validLetters:
char_only0 += char
name = char_only0
The problem lies with the 'in' part of the statement, it only works if the input is a single number (eg. '6'), but it accepts two or more numbers (eg. '65') because '65' (unlike '6') is not in validNumbers.
I want it to scan the entire input and ask again if it only consists of numbers, as you can see it takes these out (plus any special characters) at the end.
There are .isalpha() solutions, however, they don't allow whitespaces, which are required if the user inputs their full name!
I have been chipping away at this problem for hours know, someone out there is probably able to solve this for me. Thanks in advance.
Upvotes: 0
Views: 1080
Reputation: 2700
name.isalpha()
is what you are looking for I think and correct me if I'm wrong. Also, to deal with the whitespace just remove the spaces using name.replace(' ','')
so your while loop will look like
while name == "" or not name.replace(' ','').isalpha():
This will keep you from needing to strip out numbers and special characters after the while loop. Also, since replace doesn't change name in place will be unaffected and will retain any spaces if the user inputs their full name
Upvotes: 1
Reputation: 577
I would advice dropping in
and use a regular expression, because this is what they're good at!
So in your name validation case:
import re
name = '123 Full Name'
valid_pattern = re.compile('^[a-zA-Z0-9 ]+$')
if re.match(valid_pattern,name):
print 'Valid Name'
else:
print 'Invalid Name!'
Upvotes: 1