Python re.sub()在不匹配时给出Nameerror

Python re.sub()在不匹配时给出Nameerror,python,regex,Python,Regex,因此,我试图搜索和替换csv文件中的文本行,如果re.sub()找不到任何匹配项,我就会不断从中出错 如果一行中的文本是 text = "a00123 一二三四五" 我的密码是 import re html = "www.abcdefg.com/" text = "a00123 一二三四五" namelist_raw = re.sub(r'([a-z])00(\d{3})',r'\1-\2',text) p = re.findall(r'\w',namelist_raw) if p: q

因此,我试图搜索和替换csv文件中的文本行,如果re.sub()找不到任何匹配项,我就会不断从中出错

如果一行中的文本是

text = "a00123 一二三四五"
我的密码是

import re
html = "www.abcdefg.com/"
text = "a00123 一二三四五"
namelist_raw = re.sub(r'([a-z])00(\d{3})',r'\1-\2',text)
p = re.findall(r'\w',namelist_raw)
if p:
  q = re.findall(r'([a-z]-\d{3})',namelist_raw)
  for namelist in q:
    print(namelist)
else:
  namelist = "failed"

link = html + namelist
print(link)
因此,我应该得到一个结果

www.abcdefg.com/a-123
所以这没问题。 但是如果文本是这样的

text = "asdfdsdfd123 一二三四五"
我将获得名称错误,说明名称“名称列表”未定义 为什么呢?我想在我已经写过的if-else语句中,如果还有什么,名字列表是“失败的”

您的
p=re.findall(r'\w',namelist\u raw)
正在从字符串中提取每个单词字符,之后,您仅在存在匹配项时才从字符串中提取值。你不需要那张支票

接下来,只有当
[a-z]-\d{3}
有匹配项时,才会填充
名称列表
,但如果没有匹配项,则不会填充它。你也需要考虑这种情况

使用


请参阅。

此代码未编译,是否确实共享了所有相关行?oops@WiktorStribiżew sorry忘记键入其他行。我得到
www.abcdefg.com/a-123
,请参见是,但如果您将文本替换为“asdfd123一二三四五", 您将收到一个错误,说明未在@WiktorStribiżewTry定义名称“namelist”
import re
html = "www.abcdefg.com/"
text = "a00123 一二三四五"
p = re.findall(r'([a-z])00(\d{3})', text)  # Extract a list of tuples
namelist = []                              # Init the list
for letter, number in p:                  
  namelist.append(f"{letter}-{number}")    # Populate namelist with formatted tuple values

if len(namelist):                          # If there was a match
  namelist = "/".join(namelist)            # Create a string by joining namelist items with /
else:
  namelist = "failed"                      # Else, assign failed to the namelist

link = html + namelist
print(link)