0

Here's what my code looks like...

if re.match('[a-z]',usrInput):
    run onlyLetters function
elif re.match('[0-9]',usrInput):
    run onlyNumbers function
elif re.match('[a-z0-9]',usrInput):
    run lettersAndNums function

The problem is, if I enter text such as '2394jsdkfjsdkm', it will read as onlyLetters because it satisfies the first condition in the if statement. I would really like an input like this to be lettersAndNums. How do I need to alter the code?

1

2 Answers 2

3

If you just want to see if a string is all numbers, letters, or alphanumeric:

if usrInput.isalpha():
    # all letters
elif usrInput.isdigit():
    # all numbers
elif usrInput.isalnum():
    # all letters or numbers

Note that this allows both upper- and lowercase letters; if you want only lowercase letters add and usrInput.islower().

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

Comments

1

Your code only checks that the first character matches the pattern. If you want to make sure that all the characters in in string match the pattern, use [pattern]*$, like so:

if re.match('[a-z]*$',usrInput):
    run onlyLetters function
elif re.match('[0-9]*$',usrInput):
    run onlyNumbers function
elif re.match('[a-z0-9]*$',usrInput):
    run lettersAndNums function

This is because * means "any number of the character," and $ means "end of the string."

1 Comment

these patterns will match an empty string. I think it is better to use + insead of *.

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.