Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

applying a filter on a string in python

I have a user typing in his username and I only want valid strings to pass through, meaning only characters in [a-zA-Z0-9]. I am pretty new to python and unsure of the syntax.

Here's an example of what I want in code, which is to check through the username and return false upon a illegal character.:

def _checkInput(input):
     for char in input:
          if !(char in [a-zA-Z0-9]):
               return False
     return True

Thanks!

like image 549
KaiserJohaan Avatar asked Jun 12 '26 14:06

KaiserJohaan


2 Answers

There is a method in string called isalnum. It does what you are trying to achieve.

In [7]: 'ab123fd'.isalnum()
Out[7]: True

In [8]: 'ab123fd **'.isalnum()
Out[8]: False
like image 140
gruszczy Avatar answered Jun 15 '26 04:06

gruszczy


You need isalnum:

>>> name = raw_input('Enter your name: ')
Enter your name: foo_bar
>>> name.isalnum()
False
>>> name = raw_input('Enter your name: ')
Enter your name: foobar
>>> name.isalnum()
True
like image 40
user225312 Avatar answered Jun 15 '26 05:06

user225312



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!