I suck at this
I suck at this

Reputation: 23

re.sub() gives Nameerror when no match

So I'm trying to search and replace rows of texts from a csv file, and I keep getting errors from it if re.sub() can't find any matches.

Say if the text in a row is

text = "a00123 一二三四五"

And my codes are

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)

so for this i should be getting a result of

www.abcdefg.com/a-123

so that's no problem. but if the text is something like this,

text = "asdfdsdfd123 一二三四五"

I'll get Nameerror saying name 'namelist' is not defined Why is that? I thought at the if else statement I've already wrote if anything else, namelist is "failed"

my code

Upvotes: 1

Views: 255

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627101

Your p = re.findall(r'\w',namelist_raw) is extracting every word char from a string, and later, you only extract the values from the string if there were matches. You do not need that check.

Next, namelist is only populated if there is a match for [a-z]-\d{3}, but if there is no match, you do not get it populated. You need to account for that scenario, too.

Use

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)

See the Python demo.

Upvotes: 1

Related Questions