我有一个简单的函数,如果它不匹配,应该输出一个基于模式或None的前缀。试着做海象似乎不起作用。有什么想法吗?
import re
def get_prefix(name):
if m := re.match(f'^.+(\d\d)-(\d\d)-(\d\d\d\d)$', name) is not None:
return m.group(3) + m.group(2) + m.group(1)
get_prefix('abc 10-12-2020')回溯
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in get_prefix
AttributeError: 'bool' object has no attribute 'group'发布于 2021-05-12 10:39:05
您将m设置为re.match(f'^.+(\d\d)-(\d\d)-(\d\d\d\d)$', name) is not None,这是一个布尔值。
你可能是说
if (m := re.match(f'^.+(\d\d)-(\d\d)-(\d\d\d\d)$', name)) is not None:但无论如何,你不需要is not None。火柴是真实的,没有人是假的。所以你只需要:
if m := re.match(f'^.+(\d\d)-(\d\d)-(\d\d\d\d)$', name):(可以说,在使用赋值表达式时使用()是更好的做法,以明确所分配的内容。)
https://stackoverflow.com/questions/67501932
复制相似问题