Home > Blockchain >  check if a string only contains specific characters?
check if a string only contains specific characters?

Time:10-18

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!

CodePudding user response:

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

CodePudding user response:

You could use a regex, but as the task only involves checking that characters belong to a set, it will 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))
  • Related