-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!

1
  • I suggest you look in the internet about "regular expressions" or regex Commented Oct 18, 2021 at 7:40

2 Answers 2

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
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))
3
  • 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
    Commented Oct 18, 2021 at 7:52
  • @Expurple sure regex are nice when more constraints apply, I had not seen the length constraint in question ;)
    – mozway
    Commented Oct 18, 2021 at 7: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 or similar
    – Expurple
    Commented Oct 18, 2021 at 8:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.