0

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.

1
  • I don't understand why you are allowing numbers in the first place if you are just going to strip them out after. Commented Oct 6, 2015 at 13:13

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the great hint @SirParselot, perhaps you could review the edits I have made to my question. Thank you a lot.
@ProGrammer I'm not quite sure what you are asking but I would recommend posting that as a new question since it is quite a bit different than this one.
1

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!'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.