0

I am coding a simple program in which I would like to have the user input a string and then my code will check from another string of characters (that are not allowed in the string).

The string of characters that are not allowed are:

invalidChar = (@,#,£,{,[,},],:,;,",',|,\,/,?,~,`)

For example, if the user inputs "testing@3testing" I would like the code to tell the user that there is a character in the input that is not allowed.

The way I originally thought was to use:

if password[i]=="@":
  booleanCheck = True

but this would have to be repeated several times over and this would make for messy code.

Thanks in advance!

freginold
  • 3,946
  • 3
  • 13
  • 28

3 Answers3

0

You can test a character against a list of characters like this:

invalidChar = ['@','#','£','{','[','}',']',':',';','"','\'','|',
               '\\','/','?','~','`']

input_string = 'testing@3testing'

# Let's define our logic in a function so that we can use it repeatedly
def contains_invalid_char(s):  # here we name our input string s
    for element in s:          # lets iterate through each char in s
        if element in invalidChar:  # If its in the set, do the block
            return True
    return False               # If we made it this far, all were False

# Then you can use the method to return a True or False, to use in a conditional or a print statement or whatever, like

if contains_invalid_char(input_string):
    print("It was a bad string")
Shawn Mehan
  • 4,513
  • 9
  • 31
  • 51
0

Make a set of invalid characters, and then check each character in your password against that set.

def has_invalid(password):
    invalidChar = set(['@','#','£','{','[','}',']',':',';','"','\'','|','\\','/','?','~','`'])
    return any(char in invalidChar for char in password)

Note that some of the characters need to be escaped

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
0

You can do something like this:

>>> invalidChar = ('@','#')
>>> password ="testing@3testing"
>>> if any(ch in password for ch in invalidChar):
    booleanCheck = True

>>> booleanCheck
True
Tabaene Haque
  • 576
  • 2
  • 10