我们有
matches = re.findall(r'somewhat', 'somewhere')
我们可以简化这个
if len(matches) > index:
return matches[index]
else:
return 'default'
或
return matches[index] if len(mathes) > index else 'default'
类似于 JS 的东西
return matches[index] || 'default'
我们可以简单地使用
return 'somewhere'.match(/somewhat/)[index] || 'default'
最佳答案
这样的事情可能会有所帮助:
>>> reg = re.compile('-\d+-')
>>> reg.findall('a-23-b-12-c') or ['default']
['-23-', '-12-']
>>> reg.findall('a-b-c') or ['default']
['default']
编辑
丑陋的一句台词
(reg.findall('a-b-c')[index:] or ['default'])[0]
关于Pythonic 获取数组元素,如果不存在则获取默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6258081/