I'm a python newbie, using the cx_Oracle 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:
('SYSTEM',)
('SYSAUX',)
('UNDOTBS1',)
('TEMP',)
('USERS',)
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:
tablespaceNames.append(result[2:-3])
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?
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 = [
('SYSTEM',),
('SYSAUX',),
('UNDOTBS1',),
('TEMP',),
('USERS',)
]
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]
print(sdata)
The output you will see is
['SYSTEM', 'SYSAUX', 'UNDOTBS1', 'TEMP', 'USERS']
Then print out each of the strings in the tuple:
for s in sdata:
print(s)
The output from this code is
SYSTEM
SYSAUX
UNDOTBS1
TEMP
USERS
See - no quotes!
tableNameSpaces = [item [0][2:-3] for item in cursor]
The quotes will be in, though, since you're dealing with string literals.
Once you print them, however, the quotes will be gone.
As nicarus pointed out to me, probably you don't want to truncate your string literals at all, though I thought that's what you wanted.
In that case it would simply be:
tableNameSpaces = [item [0] for item in cursor]
Related
From a python function, I get the following output:
['(0.412169, mississippi)']
The type indicates that it is a list. I want to extract the values from the list and save it as separate elements. I tried various functions to convert list to tuple, list to str, extracting the element by Index from the tuple or str, nothing worked out. When I try to extract the element by index, I either get '(' for the first element index 0, or when I try to extract through a iterator function, I get all the values split up like the full data set as a string.
How do I get values separately.
You can iterate over your data, remove the parentheses using slicing and split the string by comma to create a list, which will be appended to your output payload:
data = ['(0.412169, mississippi)', '(0.412180, NY)']
extracted_values = []
for d in data:
extracted_values += d[1:-1].split(",")
print(extracted_values)
# output: ['0.412169', ' mississippi', '0.412180', ' NY']
Your list content a string, not a list.
If you want to extract the content of a string, use the "eval" statement
my_tuple = eval("(0.412169, 'mississippi')")
Note that the "eval" function can be dangerous, because if your string content python code, it could be executed.
The folowing expression works fine, returning the values that match the values list:
[...].find({"FieldName":{"$in":["Value1", "Value2", "Value3"]}})
But i have the list of values in a list object, like this:
valuesList = list()
valuesList.append("Value1")
valuesList.append("Value2")
valuesList.append("Value3")
But using the list object, a get no results:
[...].find({"FieldName":{"$in":[valuesList]}})
I Have also tried expanding the list in a formated string, like this:
strList = ', '.join(valuesList)
[...].find({"FieldName":{"$in":[strList]}})
but also, no results.
Note: If i force the list to have only one value, it works. Only when multiple values are suplied, the result is blank.
Any ideas on how to use "$in" in pymongo with a list of values in a list object?
I believe your problem is the fact that you have a list inside of a list.
Instead of:
[...].find({"FieldName":{"$in":[valuesList]}})
Try:
[...].find({"FieldName":{"$in":valuesList}})
I have a list:
listA = ['1,2,3,4,5']
where it is in string format. I want to perform a simple function that removes the last digit in the string, which in this case would be 5 and print it out.
I've tried something
listA = ['1,2,3,4,5']
for i in listA:
print(listA.pop())
What i tried is wrong as I'm not familiar with using pop on strings.
What you have is not a list of integers. It is a list with a single element, that element is a string of comma separated integers
You're not using i
You're iterating over the list and mutating it as you do so. Do not do this, because it does not give you the behaviour you expect.
I would recommend a while loop instead. First, fix your array.
listA = listA[0].split(',')
Now, iterate over it.
while listA:
print(listA.pop())
You use the truthiness of a nonempty list to keep iterating over it. This removes all the digits. However, if you just want the last digit and nothing more, call listA.pop() only once.
If you don't want to fix your array, you should extract the last digit like this:
listA = ['1,2,3,4,5']
print(int(listA[0][-1])) # [0] gets the string, [-1] gets the last character in the string
This is ungainly, so I recommend fixing your array instead.
The previous answer is giving you the last character. You can also extract the last value using split which will break up text based on a defined delimiter:
listA = ['1,2,3,4,5']
print( listA[0].split(',')[-1] )
Im pretty new to Python.
I have a list which looks like the following:
list = [('foo,bar,bash',)]
I grabbed it from and sql table (someone created the most rubbish sql table!), and I cant adjust it. This is literally the only format I can pull it in. I need to chop it up. I can't split it by index:
print list[0]
because that just literally gives me:
[('foo,bar,bash',)]
How can I split this up? I want to split it up and write it into another list.
Thank you.
list = [('foo,bar,bash',)] is a list which contains a tuple with 1 element. You should also use a different variable name instead of list because list is a python built in.
You can split that one element using split:
lst = [('foo,bar,bash',)]
print lst[0][0].split(',')
Output:
['foo', 'bar', 'bash']
If the tuple contains more than one element, you can loop through it:
lst = [('foo,bar,bash','1,2,3')]
for i in lst[0]:
print i.split(',')
I'm trying to use a Class (adns-python) which is expecting a list in the format:
domain_names = ["google.com", "yahoo.com"]
This is working when I declare the list that way manually. However, I'm trying to use a list returned from mysql using python-mysqldb.
When I look at what is being returned from mysql using:
type(mysql_rows)
This also shows as a list, but when view the result:
print(mysql_rows)
I can see the list is in the format:
[('google.com',), ('yahoo.com',)]
I've tried forcing the output to a list again using list(mysql_rows) which didn't work. I've tried parsing the text manually to make it look like the list using:
text_rows = "[" + ", ".join'"%s"' % i for i in mysql_rows = "]"
Which then shows as the correct format, but it is a string not a list so this doesn't work either.
This is my first few days learning python, so I'm sorry if this is an obvious/stupid question.
Thanks
The list is a list of tuples. A simple
lst = [x for x, in mysql_rows]
should be sufficient.
mysql returns a list of tuples. Each tuple is a result row in your result set. If you want a list of only the first "column" in the result, try this:
first_column = [x[0] for x in mysql_rows]