python - 检查字符串是否仅包含特定字符?
问题描述
我需要检查一个字符串(密码验证器)是否包含python中的特定字符和长度。条件之一是字符串pwd 仅包含字符 a-z、AZ、数字或特殊字符“+”、“-”、“*”、“/”。
块引用
这些实用程序应该可以帮助我解决它(但我不明白):
- 使用isupper/islower判断字符串是大写还是小写
- 使用isdigit检查是否为数字
- 使用in运算符检查字符串中是否存在特定字符。
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())
感谢您的帮助!
解决方案
我们可以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
推荐阅读
- getstream-io - 是否可以在 GetStream Channel 中过滤消息?
- reactjs - reactjs中我的componentDidUpdate会发生什么?
- python - 在后台不断运行python脚本是否有问题?
- servicenow - 如何在 Servicenow 中做“SQL: MINUS Operator”?
- javascript - 数组中的元素无法识别
- r - 如何防止或删除或替换 glm 输出统计中的 NA 值?
- google-app-engine - Google Cloud API:无法使用 App Engine 服务帐户创建域映射
- java - 如何从 Java 进行 Amazon AWS API 调用?
- javascript - PHP (Laravel) + MySQL + JS 命名约定
- docker - 无法在客户端 http 请求上运行 docker-compose up 完成时间太长