how to pass list values through url - python

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...

Related

how apply conditional statement on sql query result in 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.

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}')

Maya, Python, How do i get the name of an object based on vertex selection?

I got the code working like this until i realized that the vertex index changes for geometry with over 100 vertices...
I assumed i could just split the string and everything would be dandy
import maya.cmds as mc
selPoints = mc.ls(sl = True) # list of names of selected vertices
objName = (str(selPoints[0]))[:-9]
print selPoints
print objName
Heres what it returned:
[u'pCylinder25.vtx[4]', u'pCylinder25.vtx[24]']
pCylinder
I'm trying to hack off the portion with '.vtx[integer]'
I may be going about this completely wrong, and there may be a dead simple way to do this.
Thanks
You can get the object from any valid selection string with the -o flag:
cmds.ls("pCube1.vtx[0]", o=True)
# pCubeShape1
Note that will be the shape, not the transform -- that's Maya being pedantic but it is correct. The transform would be
cmds.listRelatives(cmds.ls("pCube1.vtx[0]", o=True), p=True)
You may also find it helpful to split the components using partition:
object, _, component = "pCube1.vtx[0]".partition(".")
where the _ is python slang for 'ignore me'.
Wouldn't it be awesome if it were easy to get the object from Maya? From experience, I know it can be frustrating since MEL/maya.cmds doesn't use an object-oriented approach.
Anyhow, you should refer to the documentation often for more info on the variety of string methods you can use. Really comes in handy all the time!
To answer your question, you can use .split or .find, whichever you prefer.
print selPoints[0].split('.vtx')[0]
print selPoints[0][0:selPoints[0].find('.vtx')]
The split method returns a list of strings created by the delimiter string '.vtx'. Then, taking the first element from that list will always be the object name.
The find method returns the index of the substring '.vtx', so the second example simply uses slicing syntax to return the correct string.
just for stuff, using vanilla maya commands:
as mentioned with ls:
cm.ls("pCube1.vtx[0]", o=1) # will return shape pCubeShape1
with plugNode (opposite plugAttr):
cm.plugNode("pCube1.vtx[0]") # will return transform pCube1

How do I get a formatted list of methods from a given object?

I'm a beginner, and the answers I've found online so far for this have been too complicated to be useful, so I'm looking for an answer in vocabulary and complexity similar to this writing.
I'm using python 2.7 in ipython notebook environment, along with related modules as distributed by anaconda, and I need to learn about the library-specific objects in the course of my daily work. The case I'm using here is a pandas dataframe object but the answer must work for any object of python or of an imported module.
I want to be able to print a list of methods for the given object. Directly from my program, in a concise and readable format. Even if it's just the method names in a list by alphabetical order, that would be great. A bit more detail would be even better, an ordering based on what it does is fine, but I'd like the output to look like a table, one row per method, and not big blocks of text. What i've tried is below, and it fails for me because it's unreadable. It puts copies of my data between each line, and it has no formatting.
(I love stackoverflow. I aspire to have enough points someday to upvote all your wonderful answers.)
import pandas
import inspect
data_json = """{"0":{"comment":"I won\'t go to school"}, "1":{"note":"Then you must stay in bed"}}"""
data_df = pandas.io.json.read_json(data_json, typ='frame',
dtype=True, convert_axes=True,
convert_dates=True, keep_default_dates=True,
numpy=False, precise_float=False,
date_unit=None)
inspect.getmembers(data_df, inspect.ismethod)
Thanks,
- Sharon
Create an object of type str:
name = "Fido"
List all its attributes (there are no “methods” in Python) in alphabetical order:
for attr in sorted(dir(name)):
print attr
Get more information about the lower (function) attribute:
print(name.lower.__doc__)
In an interactive session, you can also use the more convenient
help(name.lower)
function.

Python-How can i change part of a row in a CSV file?

I have a CSV file with some words in, followed by a number and need a way to append the number; either adding 1 to it, or setting it back to 1.
Say for instance I have these words:
variant,1
sixty,2
game,3
library,1
If the user inputs the number sixty, how could I use that to add one onto the number, and how would I reset it back to 1?
I've been all over Google+Stackoverflow trying to find an answer, but I expect me not being able to find an answer was due more to my inexperience than anything.
Thanks.
This is a quick throw together using fileinput. Since I am unaware of the conditions for why you would decrease or reset your value, I added it in as an keyword arg you can pass at will. Such as
updateFileName(filename, "sixty", reset=True)
updateFileName(filename, "sixty", decrease=True)
updateFileName(filename, "sixty")
The results of each should be self-explanatory. Good luck! I wrapped it in a Try as I had no clue how your structure was, which will cause it to fail ultimately either way. If you have spaces you will need to .strip() the key and value.
import fileinput
def updateFileName(filename, input_value, decrease=False, reset=False):
try:
for line in fileinput.input(filename, inplace=True):
key, value = line.split(",")
if key == input_value:
if decrease:
sys.stdout.write("%s,%s"(key, int(value) - 1)
elif reset:
sys.stdout.write("%s,%s"(key, 1)
else:
sys.stdout.write("%s,%s"(key, int(value) + 1)
continue
sys.stdout.write(line)
finally:
fileinput.close()
Without knowing when you want to switch a number to 1 and when you want to add 1, I can't give a full answer, but I can set you on the right track.
First you want to import the csv file, so you can change it around.
The csv module is very helpful in this. Read about it here: http://docs.python.org/2/library/csv.html
You will likely want to read it into a dictionary structure, because this will link each word to it's corresponding number. Something like this make dictionary from csv file columns
Then you'll want to use raw_input (or input if you are using Python 3.0)
to get the word you are looking for and use that as the key to find and change the number you want to change. http://anh.cs.luc.edu/python/hands-on/handsonHtml/handson.html#x1-490001.12
or http://www.sthurlow.com/python/lesson06/
will show you how to get one part of a dictionary by giving it the other part and how to save info back into a dictionary.
Sorry it's not a direct answer. Maybe someone else will write one up, but it should get you started,
This is very probably not the best way to do it but you can load your csv file in an array object using numpy with the help of loadtxt().
The following code is going to give you a 2 dimension array with names in the first column and your numbers in the second one.
import numpy as np
a = np.loadtxt('YourFile',delimiter=',')
Perform your changes on the numbers the way you want and use the numpy savetxt() to save your file.
If your file is very heay, this solution is going to be a pain as loading a huge array takes a lot of memory. So consider it just as a workaround. The dictionary solution is actually better (I think).

Categories