How to only allow digits, letters, and certain characters in a string in Python?

Question:

I want to make a password checker but how do I make it so I can write an error if there are characters other than digits, upper/lowercase and (,),$,%,_/.

What I have so far:

import sys
import re
import string
import random

password = input("Enter Password: ")
length = len(password)
if length < 8:
    print("nPasswords must be between 8-24 charactersnn")
elif length > 24:
    print ("nPasswords must be between 8-24 charactersnn")

elif not re.match('[a-z]',password):
        print ('error')
Asked By: Pootato

||

Answers:

Try

elif not re.match('^[a-zA-Z0-9()$%_/.]*$',password):

I can’t tell if you want to allow commas. If so use ^[a-zA-Z0-9()$%_/.,]*$

Answered By: MisterMystery

You need to have a regular expression against which you will validate:

m = re.compile(r'[a-zA-Z0-9()$%_/.]*$')
if(m.match(input_string)):
     Do something..
else
    Reject with your logic ...
Answered By: Gurvinder Singh

With Python, you should be raising exceptions when something goes wrong:

if re.search(r'[^a-zA-Z0-9()$%_]', password):
    raise Exception('Valid passwords include ...(whatever)')

This searches for any character in the password that is not (^) in the set of characters defined between the square brackets.

Answered By: Rob Bailey

If you want to avoid using RegEx, you can try this self-explanatory solution

allowed_characters=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','1','2','3','4','5','6','7','8','9','0','(',')','$','%','_','/']

password=input("enter password: ")
if any(x not in allowed_characters for x in password):
  print("error: invalid character")
else:
  print("no error")
Answered By: Sim Son
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.