通过模块re匹配字符串,如下,判断字符串str2是否在str1中
import re
str1 = "aabcd"
str2 = "abc"
match = re.compile(str2).search(str1).group()
print(match)
这样写,是为了代码的简洁,但是容易引起报错:AttributeError: 'NoneType' object has no attribute 'group' ,分析原因发现当匹配不到元素,之后又调用了group()方法造成的。因此,代码进一步优化:
import re
str1 = "aabd"
str2 = "abc"
match = re.compile(str2).search(str1)
if match:
print(match.group())
elif match == None:
print("无法匹配")
本文探讨了使用Python的re模块进行字符串匹配时可能遇到的AttributeError,并提供了一种更安全的代码实现方式,避免了当目标字符串未找到匹配项时出现的错误。
4万+





