首页 > 解决方案 > 在 python 中使用 Regex 进行验证码验证

问题描述

您好我正在尝试使用正则表达式在 python 中验证一个简单的验证码

import re

captcha = "10 + 5"
numbers = re.findall('\d+', captcha)
num1 = int(numbers[0])
num2 = int(numbers[1])
sym = re.findall('\D+', captcha)
operator = sym[0]
# print(operator)
# captcha_answer = 0
if operator == "+":
    captcha_answer = num1 + num2
if operator == "-":
    captcha_answer = num1 - num2
if operator == "*":
    captcha_answer = num1 * num2
print("captcha_answer =", captcha_answer)

我需要答案 15,但我收到一条错误消息,提示“名称 'captcha_answer' 未定义”,或者如果为 captcha_answer 定义一个错误值(如 0),则输出为 0 如何解决此问题。

提前致谢

标签: pythonregexautomation

解决方案


operator+ (带有 blancs arround),因此它与您的 if 条件不匹配。删除空格使您的代码工作:

operator = sym[0].strip()

输出:

captcha_answer = 15

推荐阅读