为了账号安全,请及时绑定邮箱和手机立即绑定

每当任务(patternstart.finditer 中的匹配)返回 None 时,如何创建操作?

每当任务(patternstart.finditer 中的匹配)返回 None 时,如何创建操作?

吃鸡游戏 2023-06-27 13:48:44
每当任务(对于patternStart.finditer(TestString) 中的匹配)未找到匹配项时,我都会尝试打印(未找到匹配项)。我一直坚持这个没有任何成功。任何意见,将不胜感激。字符串“jeke”故意不包含数字,因此找不到匹配项。TestString = 'jeke'patternStart = re.compile(r'\d')cnt = 0  # Initialize the counterwanted1 = [1]  # Defines the 1-based IDs of the matches you want to displaywanted2 = [2]  # Defines the 1-based IDs of the matches you want to displayfor match in patternStart.finditer(TestString):    cnt += 1    if cnt in wanted1:        out = match.group()    else:        print('match was not found')我已经尝试过了。if match.group() is None:    print('match was not found')if out is None:    print('match was not found')
查看完整描述

1 回答

?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

您可以使用cnt来确定是否找到任何匹配项:


for match in patternStart.finditer(TestString):

    cnt += 1

    if cnt in wanted1:

        out = match.group()

if cnt == 0:

    print('match was not found')

或者使用单独的found_match变量:


found_match = False

for match in patternStart.finditer(TestString):

    found_match = True

    cnt += 1

    if cnt in wanted1:

        out = match.group()

if not found_match:

    print('match was not found')


查看完整回答
反对 回复 2023-06-27
  • 1 回答
  • 0 关注
  • 144 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信