how apply conditional statement on sql query result in python - python

In python , i want to apply following if condition on mysql result. but it is not able to compare the result, what i do??
In this code there is table named as 'mansih' but still it's not printing 'hello'.
dir=ptr.execute('show tables')
for i in ptr.fetchall():
print(i)
if i== 'mansih':
print('hello')
the output of this code just printing the result of print(i). output is
('3432fddf',)
('dgdfdf232342334243432',)
('man456',)
('mansih',)
here i expect to print hello but it's not printed. so please provide any solution using which i can check whether given touple exist in database or not.

As you can see in your comment:
('3432fddf',) ('dgdfdf232342334243432',) ('man456',) ('mansih',)
You get tuples, and not strings, from fetchall. It should work if you modify it to if i[0] == 'mansih':, so as to fetch the first element of the tuple – which is the string you expect.
Two important lessons from this are:
You can use the (interactive, optionally) interpreter to test your outputs, and you should make sure that you understand what you see. This could spare you lots of head scratching.
Take a look at documentation if something doesn't work as expected, to make sure you understand how your tools work.

Related

How to show all items of a list in Python?

I have around 10K rows in a dataframe. I want to copy-paste all items then apply them all to my SQL query as my filter.
Here is how I convert to a list
list_a = df['col'].to_list()
When I tried to print out the list it only shows me 1k of the items. I tried to set pd.set_option('display.max_rows', None) but it seems doesn't work. It only works for pandas dataframe.
My output is,
>>> list_a
>>> ['a1',
'a2',
'a3',
till 'a1000' then it ignore the rest of 9k with
...
]
Can I get all 10k items print out?
As #Barmar points out in their comments, this print issue is not related to pandas because the pandas.series.to_list() function returns a list object.
Also #Thornily is stating that this is related to your python console trying to conserve resources. The reason python uses summarization (...) is because printing an excessive number of lines is slow and will be very difficult to visual read through the output.
Finally, I think #BENY's comment can probably help provide insight into why you need to print this many. Like #Drakax has pointed out, you can use len(list_a) to verify the list has all 10,000 items in it.
I am assuming that the OP doesn't actually need to read all 10,000 records and that they likely want to know WHY they can't override the summarization (...). Unfortunately, I am still working on the WHY answer. I have tried changing the default preferences in my console and using numpy.set_printoptions(threshold=sys.maxsize) but I still get the elipsis. I will keep trying to answer the WHY question and will update this post if I find a good answer.
For now, IF you want a HOW answer, you can use the very slow method below. Keep in mind, I do not recommend printing the output to your console for the reasons stated above. But if you ABSOLUTELY have to print to your console you can do this:
for n in list_a:
print(n)
or you can also convert using the list function to force the object to a python list and print multiple values on each console line:
list_a = list(list_a)
print(list_a)

Finding a set of values

I have a curve_hex generator, it uses two coordinates, I'm looking for only one coordinate. The script searches for one coordinate value easily, but if I specify several coordinates for the search, then it does not find anything.
wanted='58611774815559422402170859520215717661755632997646071327165159211728464937238'
curve_hex='(58611774815559422402170859520215717661755632997646071327165159211728464937238, 108722706890170119196943746054760504186165603293283329661416022207913727808252)'
if str(curve_hex).find(wanted)!=-1:
print (curve_hex[str(curve_hex).find(wanted):str(curve_hex).find(wanted)+len(wanted)])
else:
print ('not')
One value is found normally. But if I add several values, the script writes an error
wanted='58611774815559422402170859520215717661755632997646071327165159211728464937238', '108722706890170119196943746054760504186165603293283329661416022207913727808252'
curve_hex='(58611774815559422402170859520215717661755632997646071327165159211728464937238, 108722706890170119196943746054760504186165603293283329661416022207913727808252)'
if str(curve_hex).find(wanted)!=-1:
print (curve_hex[str(curve_hex).find(wanted):str(curve_hex).find(wanted)+len(wanted)])
else:
print ('not')
Tell me how to do it right. What am I doing wrong. I have just started learning python.
Very exciting that you are learning python, I would also suggest that you might want to spend some time in the stackoverflow section explaining how to ask a question because I am not 100% sure what you are trying to achieve with your code.
From my understanding, if you are happy with your if else conditions, and your only problem is that you can’t add multiple values to wanted. I would convert wanted to a list that includes all your wanted values, and loop over those.
Something like this:
wanted = ['586..{copy the whole value here}', '108...{copy the value here}']
curve_hex='(58611774815559422402170859520215717661755632997646071327165159211728464937238, 108722706890170119196943746054760504186165603293283329661416022207913727808252)'
for value in wanted:
if str(curve_hex).find(value)!=-1:
print (curve_hex[str(curve_hex).find(value):str(curve_hex).find(value)+len(value)])
else:
print ('not')
Edit: formatting and typos
You are misleadiong some basic concepts:
Difinitions like this result in diferent types
wanted='58611774815559422402170859520215717661755632997646071327165159211728464937238'
type(wanted) # string
wanted='58611774815559422402170859520215717661755632997646071327165159211728464937238', '108722706890170119196943746054760504186165603293283329661416022207913727808252'
type(wanted) # tuple
curve_hex='(58611774815559422402170859520215717661755632997646071327165159211728464937238, 108722706890170119196943746054760504186165603293283329661416022207913727808252)'
type(wanted) # string
So you should choose a type first. Tuple is the best case.
wanted=('58611774815559422402170859520215717661755632997646071327165159211728464937238', '108722706890170119196943746054760504186165603293283329661416022207913727808252')
curve_hex=('58611774815559422402170859520215717661755632997646071327165159211728464937238', '108722706890170119196943746054760504186165603293283329661416022207913727808252')
for i in wanted:
for x,j in enumerate(curve_hex):
if i in j:
print(f'{i} in {curve_hex} at position {x}')

Pythonic way not working with list

I have a seemingly simple problem, but I the code that I believe should solve it is not behaving as expected -- but a less elegant code that I find functionally equivalent behaves as expected. Can you help me understand?
The task: create a list, drop a specific value.
The specific usecase is that I am dropping a specific list of columns of pd.df, but that is not the part I want to focus on. It's that I seem to be unable to do it in a nice, pythonic single-line operation.
What I think should work:
result = list(df.columns).remove(x)
This results in object of type 'NoneType'
However, the following works fine:
result = list(df.columns)
result.remove(X)
These look functionally equivalent to me -- but the top approach is clearer and preferred, but it does not work. Why?
The reason is that remove changes the list, and does not return a new one, so you can't chain it.
What about the following way?
result = [item for item in df.columns if item != x]
Please note that this code is not exactly equivalent to the one you provided, as it will remove all occurrences of x, not just the first one as with remove(x).
Those are definitely not functionally equivalent.
The first piece of code puts the result of the last called method into result, so whatever remove returns. remove always returns None since it returns nothing.
The second piece of code puts the list into result, then removes from the list (which is already stored in result) the item. You are discarding the return of remove, as you should. The equivalent and wrong thing to do would be:
:
result = list(df.columns)
result = result.remove(X)
The two pieces of code are not really equivalent. In the second one, the variable result holds your list. You then call remove on that list, and the element is removed. So far so good.
In the first piece of code you try to assign the return value of remove() to result, so this would be the same as:
result = list(df.columns)
result = result.remove(X)
And since remove has no return value, the result will be NoneType.

Input/Output items of the 'work' function in GNU Radio

Is there a way to print (in the terminal or to a file) the input items passed to the work function and the output items produced there? I have written a GNU radio block (in Python) and I need to access the above information.
Any help is appreciated! :)
Assuming you're using a sync_block as block type, your work function will look like this:
def work(self, input_items, output_items):
where input_items is a 2D-array. First axis is the input ports (you might have only one) and second axis is the input items. So, if you just want to print the input items of the first input port in the terminal, you can do something like:
for i in range(len(input_items[0])):
print input_items[0][i]
Since you are producing the output items yourself within the work function, you can print them in the same manner after creating them.
Still, I think you try to solve something with this question that could be solved in another (better) way. Can you specify what you're trying to do with the information gathered by the printed input/output items?

how to pass list values through url

I have written a python script where I have collected some values in a list. I need to pass on these values to an URL in a loop where in each time a different value is picked up.
i..e, I want to achieve this:
http://www.abc.com/xyz/pqr/symbol=something[i].
Here "something" is a list and I have verified that it contains the proper values. However when I pass the values to the URL, I am not getting the desired results. I have tried with URL encoding for something[i] but still it is not giving me proper results. Can someone help me?
EDIT: My example script at the moment is:
import json
script=["Linux","Windows"]
for i in xrange(len(script)):
site="abc.com/pqr/xyz/symbol=json.dumps(script[i])";
print site
I think the problem is your approach to formatting. You don't really need json if you have a list already and are just trying to modify a URL...
import json
script=["Linux","Windows"]
something = ["first","second"]
for i,j in zip(script,something):
site="http:abc.com/pqr/xyz/symbol={0}".format(j)
print i, site
This uses the .format() operator, which "sends" the values in parentheses into the string at the positions marked with {}. You could just add the strings together if it is always at the end. You could also use the older % operator instead. It does pretty much the same thing, but in this case it inserts the string j at the position marked by %s:
site="http:abc.com/pqr/xyz/symbol=%s" % (j)
Side note: I slightly prefer % because once you learn it, it can also be used in other programming languages, but .format() has more options and is the recommended way to do it since python 2.6.
Output:
Linux http:abc.com/pqr/xyz/symbol=first
Windows http:abc.com/pqr/xyz/symbol=second
You should be able to get close to what you want from this starting point, but if this is nothing like your desired output, then you need to clarify in your question...

Categories