Qwix Qwix - 1 year ago 84
Python Question

Slicing a python variable removes the whole string

I'm a python newbie, using the

python package to execute a sql query:

cursor.execute("select tablespace_name from user_tablespaces")

to retrieve a list from an oracle 11g database. The results look like this:


I need to remove the single quotes and the comma from each entry and then put it into an array, and am attempting to use python slicing to do so:

tablespaceNames = []
for result in cursor:

however, this is just giving me empty strings in my array:


Is it a problem with the object I'm getting from the query result, or am I using python slicing wrong?

Answer Source

You are slicing the tuples that represent each retrieved row rather than the strings that are the first (and only) elements of those rows. Further, you don't need to "get rid of the quotes" - that's just the interpreter doing its best to represent the data structure.

Your database returns the equivalent of the structure below - a list of tuples. Since you only selected a single field, each tuple only contains one element.

data = [

So first let's extract those single elements to give ourselves a list of strings instead of a list of tuples.

sdata = [s[0] for s in data]

The output you will see is


Then print out each of the strings in the tuple:

for s in sdata:

The output from this code is


See - no quotes!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download