首页 > 解决方案 > 检查字符串是否仅包含特定字符?

问题描述

我需要检查一个字符串(密码验证器)是否包含python中的特定字符和长度。条件之一是字符串pwd 仅包含字符 a-z、AZ、数字或特殊字符“+”、“-”、“*”、“/”。

块引用

这些实用程序应该可以帮助我解决它(但我不明白):


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())

感谢您的帮助!

标签: pythonstringvalidationpasswordscharacter

解决方案


我们可以re.search在这里使用正则表达式选项:

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

推荐阅读