fuzzylogical
fuzzylogical

Reputation: 892

Python: REGEX works in one place, but not another with same input

I will preface this with the fact that I am not a Python coder, I am just hacking this together for a quick check of the DB for my Android app. That and I'd like to turn it into a script for my webpage. That aside, I can't figure out why the code outside of the for-statement works while inside doesn't. It appears that row and row2 are identical. It pulls out the "beginner" table name fine in the first, but won't in the loop. Thanks for the help.

row = "(u'beginner',)"
print row
temp = re.search('\(u\'(.*)\',\)', row).group(1)
print temp

#getRows is a cursor fetch on a sqlite DB if that matters        
for row2 in getRows:
    print row2
    temp = re.search('\(u\'(.*)\',\)', row2).group(1)
    print temp 

OUTPUT:

Finding files... done.
Importing test modules ... 
(u'beginner',)
beginner
(u'beginner',)
done.

Ran 0 tests in 0.000s

OK

Upvotes: 0

Views: 71

Answers (1)

John Zwinck
John Zwinck

Reputation: 249404

I know why it's not working: because while the string representations of row and row2 are the same, they aren't really the same at all. Try printing type(row2) and you'll see it's a tuple. I know this because the DB API would return a tuple, not a string that looks like a tuple.

So when you have this:

row = "(u'beginner',)"

It's a string that looks like a tuple, and you can re.search it. But you shouldn't do any of this--in the DB row, you should just get the string content by row2[0] and not use re at all.

Upvotes: 2

Related Questions