3

I'm an absolute beginner trying to learn string validation. I have a variable about to store user input:

Text_input = raw_input('Type anything: ')

I want to check if Text_input contains at least one alphanumeric character. (If not, the program should print a message such as "Try again!" and ask the user to type again.) So, typing "A#" should pass but "#" should not. Any suggestions?

Ale
  • 946
  • 4
  • 17
  • 28
VillaRava
  • 157
  • 2
  • 10
  • 2
    It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ] and [ask]. – Morgan Thrapp Dec 22 '15 at 18:35
  • 6
    This is a duplicate of: http://stackoverflow.com/questions/19859282/check-if-a-string-contains-a-number – jcmack Dec 22 '15 at 18:43
  • You could loop through each character of the string with a for loop and check if it corresponds with a valid ascii alphanumeric character (65-122 for the letters and you can look up the number codes) – Ashwin Gupta Dec 22 '15 at 21:41

1 Answers1

6

This worked for me:

    Text_input = raw_input('Type anything: ')
    if any(char.isalpha() or char.isdigit() for char in Text_input):
        print "Input contains at least one alphanumeric character."
    else:
        print "Input must contain at least one alphanumeric character." 
VillaRava
  • 157
  • 2
  • 10