有没有一种优雅的单行方法来找到一个包含 7 的数字,除非它只是 7?
if re.search(r'(d+)?(7)(d+)', line):
print "Found 7 inside or beginning of a number", match.group()
else:
if re.search(r'(d+)(7)(d+)?', line):
print "Found 7 in the end of a number", match.group()
你的意思是
'7' in line and len(line) > 1
您还可以使用 str.isdigit()
检查是否所有字符都是数字。
这是一个涉及正则表达式的简单解决方案,因为您特别要求:
re.search("(7.)|(.7)", line)