SQL/Python - Adding list (with multiple entries) to SQL String - python

I have a list in Python i.e:
['E/123', 'E/145']
I want to add this to a SQL statement that I made:
WHERE GrantInformation.GrantRefNumber LIKE 'E/123'
OR GrantInformation.GrantRefNumber LIKE 'E/145'
The code I have is:
items = []
i = 0
while 1:
i += 1
item = input('Enter item %d: '%i)
if item == '':
break
items.append(item)
print(items)
refList = " OR GrantInformation.GrantRefNumber LIKE ".join(items)
The problem is, when I insert that String into my SQL it is a String so it is looking for WHERE GrantInformation.GrantRefNumber Like 'ES/P004355/1 OR GrantInformation.GrantRefNumber LIKE ES/P001452/1'
Which obviously returns nothing as 'ES/P004355/1 OR GrantInformation.GrantRefNumber LIKE ES/P001452/1' does not appear in the field.
How do i do it so the ' GrantInformation.GrantRefNumber LIKE ' is not a String?
Thank you

The preferred way to do this, is to use a ORM like SQLAlchemy, which
does the query construction for you and you dont have to make the string concentrations yourself.
join(), adds the string between all the items in the array, that is passed as argument. You would need to add the condition into the array as well:
>>> items = ['A', 'B']
>>> " OR ".join(["GrantInformation.GrantRefNumber LIKE '%s'" % num for num in items])
"GrantInformation.GrantRefNumber LIKE 'A' OR GrantInformation.GrantRefNumber LIKE 'B'"

Related

Concatenate index of a list into a string variables

I have a list
list = ['1a-b2', '2j-u3', '5k-hy', '1h-j3']
and I have a string like below
main = '{"datatype: null" "country_code":"eu","offset":0,"id":"2y-9k"}'
How can I replace the id value in string, with its respective index in the master list ?
For Eg.,
I want to replace the "1h-j3" in the main string with its index in list. This to be done in a loop for all as well.
I have tried to concatenate using +, % but they did not work, kindly help me with this. Both the list indexes and main variable are of data type string
expected output is as follows
in first loop
main = '{"datatype: null" "country_code":"eu","offset":0,"id":"1a-b2"}'
in second loop
main = '{"datatype: null" "country_code":"eu","offset":0,"id":"2j-u3"}'
in third loop
main = '{"datatype: null" "country_code":"eu","offset":0,"id":"5k-hy"}'
and so on
Well, I can think of 2 approaches, based on the type of data you have for the main variable. See below.
In case, the value is a proper JSON
import json
items_list = ['1a-b2', '2j-u3', '5k-hy', "1h-j3"]
# if main_dict was a valid json
main_dict = json.loads('{"datatype": "null", "country_code":"eu","offset":0,"id":"1h-j3"}')
main_dict["id"] = items_list.index(main_dict["id"])
main_dict = json.dumps(main_dict)
Other case, its a dirty string manipulation. May be there are better ways,
# If its not a valid JSON
str_main = '{"datatype: null" "country_code":"eu","offset":0,"id":"1h-j3"}'
import re
# Use a regex to find the key for replacement.
found = re.findall(r'"id":".*"', str_main, re.IGNORECASE)
if found and len(found) > 0:
key = found[0].split(":")[1].replace('"', '')
_id = items_list.index(key)
str_main = str_main.replace(key, str(_id))
print(str_main)
produced output
{"datatype: null" "country_code":"eu","offset":0,"id":"3"}
--UPDATE--
As per your requirement updated in question, then it will be a simple loop I assume like below.
items_list = ['1a-b2', '2j-u3', '5k-hy', "1h-j3"]
base_str = '{"datatype: null" "country_code":"eu","offset":0,"id":"_ID_"}'
for item in items_list:
main = base_str.replace('_ID_', item)
print(main)
Produces output like
{"datatype: null" "country_code":"eu","offset":0,"id":"1a-b2"}
{"datatype: null" "country_code":"eu","offset":0,"id":"2j-u3"}
{"datatype: null" "country_code":"eu","offset":0,"id":"5k-hy"}
{"datatype: null" "country_code":"eu","offset":0,"id":"1h-j3"}

How can I replace an item in a list with a string that has a space in it?

I am trying to simply replace a list item with another item, except the new item has a space in it. When it replaces, it creates two list items when I only want one. How can I make it just one item in the list please?
Here is a minimal reproducible example:
import re
cont = "BECMG 2622/2700 32010KT CAVOK"
actual = "BECMG 2622"
sorted_fm_becmg = ['BECMG 262200', '272100']
line_to_print = 'BECMG 262200'
becmg = re.search(r'%s[/]\d\d\d\d' % re.escape(actual), cont).group()
new_becmg = "BECMG " + becmg[-4:] + "00" # i need to make this one list item when it replaces 'line_to_print'
sorted_fm_becmg = (' '.join(sorted_fm_becmg).replace(line_to_print, new_becmg)).split()
print(sorted_fm_becmg)
I need sorted_fm_becmg to look like this : ['BECMG 270000', '272100'].
I've tried making new_becmg a list item, I have tried removing the space in the string in new_becmg but I need the list item to have a space in it.
It is probably something simple but I can't get it. Thank you.
You can iterate through sorted_fm_becmg to replace each string individually instead:
sorted_fm_becmg = [b.replace(line_to_print, new_becmg) for b in sorted_fm_becmg]

simple way convert python string to quoted string

i'm new to python and i'm having a select statement like following help_category_id, name, what is the most effective way to convert this string to this:
'help_category_id', 'name'
i've currently done this, which works fine, but is there a nicer and more clean way to do the same:
test_string = 'help_category_id, name'
column_sort_list = []
if test_string is not None:
for col in test_string.split(','):
column = "'{column}'".format(column=col)
column_sort_list.append(column)
column_sort = ','.join(column_sort_list)
print(column_sort)
Simple one liner using looping constructs:
result = ", ".join(["'" + i + "'" for i.strip() in myString.split(",")])
What we are doing here is we are creating a list that contains all substrings of your original string, with the quotes added. Then, using join, we make that list into a comma delimited string.
Deconstructed, the looping construct looks like this:
resultList = []
for i in myString.split(","):
resultList.append("'" + i.strip() + "'")
Note the call to i.strip(), which removes extraneous spaces around each substring.
Note: You can use format syntax to make this code even cleaner:
New syntax:
result = ", ".join(["'{}'".format(i.strip()) for i in myString.split(",")])
Old syntax:
result = ", ".join(["'%s'" % i.strip() for i in myString.split(",")])
it can be achieved by this also.
','.join("'{}'".format(value) for value in map(lambda text: text.strip(), test_string.split(",")))

Python len not working

In the code below, I am trying to use len(list) to count the number of strings in an array in each of the tags variables from the while loop. When i did a sample list parameter on the bottom, list2, it printed 5 which works, but when i did it with my real data,it was counting the characters in the array, not the number of strings. I need help figuring out why that is and i am new to python so the simplest way possible please!
#!/usr/bin/python
import json
import csv
from pprint import pprint
with open('data.json') as data_file:
data = json.load(data_file)
#pprint(data)
# calc number of alert records in json file
x = len(data['alerts'])
count = 0
while (count < x):
tags = str(data['alerts'][count] ['tags']).replace("u\"","\"").replace("u\'","\'")
list = "[" + tags.strip('[]') + "]"
print list
print len(list)
count=count+1
list2 = ['redi', 'asd', 'rrr', 'www', 'qqq']
print len(list2)
Your list construction list = "[" + tags.strip('[]') + "]" creates a string, not a list. So yes, len works, it counts the characters in your string.
Your tags construction looks a bit off, you have a dictionary of data (data['alerts']) which you then convert to string, and strip of the '[]'. Why don't use just get the value itself?
Also list is a horrible name for your variable. This possible clashes with internal values.
list = "[" + tags.strip('[]') + "]"
print list
print len(list)
Ironically, list is a string, not a list. That's why calling len on it "was counting the characters in the array"
you need to make sure that your variable is a list rather than a str,
try:
print(type(yourList))
if it shows that it is a str, then try this:
len(list[yourList)
hope this answers your question
and when you want to establish a list variable, try this:
myList = []
for blah in blahblah:
myList.append(blah)
I think these definitely solved your problem, so I hope you noticed this part.

Python: Formatting lists of lists

I'm a newbie to Python. I have the code below which basically extracts some 5 rows from a MySql table.
if keyword.lower() == 'last5':
cursor.execute('SELECT income_Ref, income_Amount FROM model_income WHERE company_MobileNumber = %s ORDER BY income_Datetime DESC LIMIT 5', [sender])
result = cursor.fetchall()
result = [list(row) for row in result]
self.respond(result)
return ()
The self.respond() kinda works like print() but it sends a text message instead.I am having trouble formatting the output. What I get from the code above is a list of lists which looks likes this:
[[u'2014-11-06fd753b-inc', u'50.0'], [u'2014-11-067d724b-inc', u'50.0'], [u'2014-11-067557d6-inc', u'50.0']]
I really wish I new how to make it look like this:
Ref:2014-11-06fd753b-inc Amount:50.0
Ref:2014-11-067d724b-inc Amount:50.0
Ref:2014-11-067557d6-inc Amount:50.0
That includes prefixing 'Ref' and 'Amount' before each respective field. I swear I have searched high and low on how to do that for a week now but I'm failing to crack it.
You can use:
self.respond("\n".join("Ref:{} Amount:{}".format(ref, amt) for ref, amt in result))
Not really beginner material, but...
Joining a string (created by formatting "Ref:{} Amount:{}") with "\n" using a generator
if keyword.lower() == 'last5':
cursor.execute('SELECT income_Ref, income_Amount FROM model_income WHERE company_MobileNumber = %s ORDER BY income_Datetime DESC LIMIT 5', [sender])
result = cursor.fetchall()
result = [list(row) for row in result]
self.respond("\n".join("Ref:{} Amount:{}".format(ref, amt) for ref, amt in result))
return ()
I left the list comprehension result = [list(row) for row in result] because I don't know what fetchall() actually returns.
Output:
Ref:2014-11-06fd753b-inc Amount:50.0
Ref:2014-11-067d724b-inc Amount:50.0
Ref:2014-11-067557d6-inc Amount:50.0
["Ref:" + i[0][2:-1] + " Amount: " + i[1][2:-1] + "\n" for i in result]

Categories