-2

I need to check a string (password validator) whether it contains specific characters and lenght in python. One of the condition is, that the string pwd only contains the characters a-z, A-Z, digits, or the special chars "+", "-", "*", "/".

Blockquote

These utilities should help me solve it (but I don't get it):

  • Use isupper/islower to decide whether a string is upper case or lower case
  • Use isdigit to check if it is a number
  • Use the in operator to check whether a specific character exists in a string.

pwd = "abc"

def is_valid():
    # You need to change the following part of the function
    # to determine if it is a valid password.
    validity = True

    # You don't need to change the following line.
    return validity

# The following line calls the function and prints the return
# value to the Console. This way you can check what it does.
print(is_valid())

I'd appreciate your help!

Kimimaro
  • 7
  • 1

2 Answers2

0

We can use re.search here for a regex option:

def is_valid(pwd):
    return re.search(r'^[A-Za-z0-9*/+-]+$', pwd) is not None

print(is_valid("abc"))   # True
print(is_valid("ab#c"))  # False
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

You could use a regex, but as the task only involves checking that characters belong to a set, it might be more efficient to just use python sets:

def is_valid(pwd):
    from string import ascii_letters
    chars = set(ascii_letters+'0123456789'+'*-+/')
    return all(c in chars for c in pwd)

examples:

>>> is_valid('abg56*-+')
True

>>> is_valid('abg 56*')
False

Alternative using a regex:

def is_valid(pwd):
    import re
    return bool(re.match(r'[a-zA-Z\d*+-/]*$', pwd))
mozway
  • 194,879
  • 13
  • 39
  • 75
  • Also, you can check the length right in the regex. For example, you want at least 8 characters: `return bool(re.fullmatch(r'[a-zA-Z\d*+-/]{8,}', pwd))` . That's the whole function, one line with regex :) – Expurple Oct 18 '21 at 07:52
  • @Expurple sure regex are nice when more constraints apply, I had not seen the length constraint in question ;) – mozway Oct 18 '21 at 07:54
  • My other comment can't be edited anymore :( I've just noticed that our character class has a bug. `+-/` will be interpreted as a range. Need to escape the `-`. That's why it's better to always double check every pattern on [regexr.com](https://regexr.com) or similar – Expurple Oct 18 '21 at 08:07