【问题标题】:Python: If statement "If not none" handlingPython:If 语句“If not none”处理
【发布时间】:2017-10-21 15:25:20
【问题描述】:

我正在使用带有 if 语句的 Python 正则表达式:如果匹配是 None,那么它应该转到 else 子句。但它显示了这个错误:

AttributeError: 'NoneType' object has no attribute 'group'

脚本是:

import string
chars = re.escape(string.punctuation)
sub='FW: Re: 29699' 
if re.search("^FW: (\w{10})",sub).group(1) is not None :
    d=re.search("^FW: (\w{10})",sub).group(1)
else:
    a=re.sub(r'['+chars+']', ' ',sub)
    d='_'.join(a.split())

每一个帮助都是很大的帮助!

【问题讨论】:

  • 你写的是is not None而不是is None,这似乎是你需要的。
  • 第一个错误是 import re
  • 即使这样它也不起作用
  • 您不能对任何对象进行分组

标签: python regex if-statement error-handling nonetype


【解决方案1】:

您的问题是:如果您的搜索没有找到任何内容,它将返回None。你不能做None.group(1),这就是你的代码。相反,请检查搜索结果是否为None——而不是搜索结果的第一组。

import re
import string

chars = re.escape(string.punctuation)
sub='FW: Re: 29699' 
search_result = re.search(r"^FW: (\w{10})", sub)

if search_result is not None:
    d = search_result.group(1)
else:
    a = re.sub(r'['+chars+']', ' ', sub)
    d = '_'.join(a.split())

print(d)
# FW_RE_29699

【讨论】:

  • 这太合乎逻辑了,谢谢!
猜你喜欢
  • 1970-01-01
  • 2011-03-23
  • 2022-07-05
  • 1970-01-01
  • 1970-01-01
  • 2011-02-12
  • 2022-01-11
  • 1970-01-01
  • 2016-05-20
相关资源
最近更新 更多