Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python pyodbc loop – remove brackets, hyphens and commas from list

I’m using the below Python script to loop around a SQL Server table and save the values to a list.
However, I don’t want the brackets \ commas etc. When I run the below the records in the list look like this:

('TN12345', )

I just want the below – how it exists in the SQL table:

TN12345

This is my script:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import pyodbc

connstr = 'DRIVER={SQL Server};SERVER=XXXXXXXXXXX;DATABASE=XXXXXXXXXXX;Trusted_Connection=yes;'
conn = pyodbc.connect(connstr)
cursor = conn.cursor()

cursor.execute("""SELECT TN_Number FROM Table""")

records = cursor.fetchall()
insertObject = []
columnNames = [column[0] for column in cursor.description]

for record in records:
    insertObject.append( dict( zip( columnNames , record ) ) )

for i in range(len(records)):
  print(records[i])

>Solution :

This

('TN12345', )

is tuple with one element, representing row in database, if you can guarantee that your query will always return exactly 1 column then you might use [0] to access single element in said tuple, in your case replace

for i in range(len(records)):
  print(records[i])

using

for i in range(len(records)):
  print(records[i][0])

alternatively you might use for loop directly (without caring about index) in following way

for record in records:
  print(record[0])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading