我在使用包含 re.match
跳过 if
并直接跳转到 else 的 python
,因此循环始终返回 for
循环时遇到问题"none"
。如果我没有 else,if
将起作用。
代码如下:
def searchBegin (searchChar):
regex = searchChar
regex += '.{2,7}'
pattern = re.compile(regex)
for (offset, line) in enumerate(lines):
if re.match(pattern, line):
return line
break
else:
return 'none'
我该如何纠正这个问题?
最佳答案
当前发生的情况是您的第一行没有匹配项,因此循环在第一次迭代中进入 else block ,并直接返回 none
。
相反,您可以执行如下操作,其中 none
在 for 循环结束后返回,您只需打印一个 no match
否则:
def searchBegin (searchChar):
regex = searchChar
regex += '.{2,7}'
pattern = re.compile(regex)
for (offset, line) in enumerate(lines):
if re.match(pattern, line):
return line
break
else:
print "no match"
return 'none'
关于python - 为什么我的代码直接跳到其他地方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33251539/