Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape a hash (#) char in python?

I'm using pyodbc to query an AS400 (unfortunately), and some column names have hashes in them! Here is a small example:

self.cursor.execute('select LPPLNM, LPPDR# from BSYDTAD.LADWJLFU')

for row in self.cursor:
    p = Patient()
    p.last = row.LPPLNM
        p.pcp = row.LPPDR#

I get errors like this obviously:

 AttributeError: 'pyodbc.Row' object has no attribute 'LPPDR'

Is there some way to escape this? Seems doubtful that a hash is even allowed in a var name. I just picked up python today, so forgive me if the answer is common knowledge.

Thanks, Pete

like image 834
slypete Avatar asked Dec 07 '22 06:12

slypete


2 Answers

Use the getattr function

p.pcp = getattr(row, "LPPDR#")

This is, in general, the way that you deal with attributes which aren't legal Python identifiers. For example, you can say

setattr(p, "&)(@#$@!!~%&", "Hello World!")
print getattr(p, "&)(@#$@!!~%&")  # prints "Hello World!"

Also, as JG suggests, you can give your columns an alias, such as by saying

SELECT LPPDR# AS LPPDR ...
like image 90
Eli Courtwright Avatar answered Dec 31 '22 21:12

Eli Courtwright


You can try to give the column an alias, i.e.:

 self.cursor.execute('select LPPLNM, LPPDR# as LPPDR from BSYDTAD.LADWJLFU')
like image 29
João Silva Avatar answered Dec 31 '22 21:12

João Silva