replace the strings with variables in python - python

The following statement works as expected and myreservation object is created.
myreservation = conn.run_instances(amiid, placement='us-east-1a', key_name='n15a',instance_type=my_instance_type,security_groups=['N-1-0-1-AutogenByAWSMP-'])
But the following does not work. I get an error in the script later because myreservation object is not created.
myreservation = ("conn.run_instances('%s', placement='us-east-1a', key_name='n15a',instance_type='%s',security_groups=['%s'])" % (amiid, my_instance_type, my_security_groups))
I need to replace the security group with variable because that will make it easy for me to change it later.
error is:
The security group '%s' does not exist
when I print that statement and run it at python console, it works as expected
And the following does not work either:
myreservation = conn.run_instances('%s', placement='us-east-1a', key_name='nov15a',instance_type='%s',security_groups=['%s']) % (amiid, my_instance_type, my_security_groups)

your second version doesn't work because you put "conn.run_instances" into the string which probably is not what you want. hard to tell from your very small code example but I'd guess:
myreservation = conn.run_instances(amiid, placement='us-east-1a', key_name='n15a',instance_type=my_instance_type,security_groups=[my_security_groups])
is what you are looking for (assuming my_security_groups is correctly set)
edit:
Why does %s does not work?
'%s' works fine if you use it correctly.
in your third example:
myreservation = conn.run_instances('%s', placement='us-east-1a', key_name='nov15a',instance_type='%s',security_groups=['%s']) % (amiid, my_instance_type, my_security_groups)
you try to use a single replacement tuple for three different strings. this does not work, you'd have to replace each string individually. something like this would probably work, but it doesn't really make sense to use string replacements if you're replacing the whole string
myreservation = conn.run_instances('%s'%amiid, placement='us-east-1a', key_name='nov15a',instance_type='%s'%my_instance_type,security_groups=['%s'my_security_groups])

Related

How to use quotation marks and full stops in Python function argument

I can't seem to get this formatting working in Python. I am trying to define a function that holds an argument on the form - "[Some].[Name]"
Can anyone tell me how I can this working? I think I have tried all combinations of ' and ", but regardless both the [.] and ["] in the argument seems to not work.
In the below code I am trying to define the argument as "VWS.co"
def get_stock_data(Company):
#This function defines the data to be collected.
#send a get request to query Company's end of day stock prices in period
global VWS_data
Stock_data = yf.Ticker(Company)
Stock_data = Stock_data.history(period="5y")
# look at the first 5 rows of the dataframe
print(Stock_data)
print(Stock_data.describe(include='all'))
get_stock_data("VWS.co")
Edit:
Using escape characters get_stock_data(""VWS.co"") got the definition working. However, something is still wrong. When I run the script it still only works using "VWS.co" as the definition. See below code, the VWS_data_with_arg works. VWS_data does not. Am i missing something really obvious here?
def get_stock_data(Company):
Stock_data = yf.Ticker("VWS.co")
Stock_data_with_arg = yf.Ticker(Company)
VWS_data = Stock_data.history(period="5y")
VWS_data_with_arg = Stock_data_with_arg.history(period="5y")
print(VWS_data) #This returns the expected values
print(VWS_data_with_arg) #This returns an empty dataset
get_stock_data("\"VWS.co\"")
You should use escape characters.
get_stock_data("\"VWS.co\"")
You can use raw strings
get_stock_data(r'"VWS.co"')

Python for maya: Why can't I use a variable in concatination with a wildcard?

I'm trying to use the "ls" python command in maya, to list certain objects with a matching string in the name in concatination with a wildcard.
Simple sample code like this:
from maya.cmds import *
list = ls('mesh*')
This code works and will return a list of objects with the matching string in the name, however, I would like to use a variable instead of hard coding in the string. More like this:
from maya.cmds import *
name = 'mesh'
list = ls('name*')
OR like this:
from maya.cmds import *
name = 'mesh'
list = ls('name' + '*')
However, in both examples, it returns an empty list unlike the first. I'm not sure why this is the case because in those examples, the string concatination should come out to 'mesh*' like the first example. I couldn't find an answer on this website, so I chose to ask a question.
Thank you.
JD
PS. If there is a better way to query for objects in maya, let me know what it's called and I'll do some research into what that is. At the moment, this is the only way I know of how to search for objects in maya.
As soon as you add quotes around your variable name like this 'name', you are actually just creating a new string instead of referring to the variable.
There are many different ways to concatenate a string in Python to achieve what you want:
Using %:
'name%s' % '*'
Using the string's format method:
'{}*'.format(name)
Simply using +:
name + '*'
All of these will yield the same output, 'mesh*', and will work with cmds.ls
Personally I stick with format, and this page demonstrates a lot of reasons why.

Loop through values of one variable to populate another variable - SPSS

I currently have the below syntax -
BEGIN PROGRAM.
import spss,spssdata
varlist = [element[0] for element in spssdata.spssdata('CARD_2_Q2_1_a').fetchall()]
varstring = " ".join(str(int(i)) for i in varlist)
spss.submit("if (Q4_2 = 2 AND CARD_2_Q2_1_a = %(varstring)s) Q4_2_FULL = %(varstring)s." %locals())
END PROGRAM.
I thought this would just loop through the values in my variable CARD_2_Q2_1_a and populate Q4_2_FULL where appropriate. It worked in long hand without Python use, but the code above doesn't change the input file at all. Any reason why this might not be working or an alternative way of doing this?
varstring will be a string of integers joined by blanks. Therefore, your test condition in the IF will never be satisfied. Hence Q4_2_FULL will never be populated. You can print out the command you are submitting to see this.
I'm not sure exactly what your desired result is, but remember that the IF command you are submitting will execute over the entire dataset.

Using Strings to Name Hash Keys?

I'm working through a book called "Head First Programming," and there's a particular part where I'm confused as to why they're doing this.
There doesn't appear to be any reasoning for it, nor any explanation anywhere in the text.
The issue in question is in using multiple-assignment to assign split data from a string into a hash (which doesn't make sense as to why they're using a hash, if you ask me, but that's a separate issue). Here's the example code:
line = "101;Johnny 'wave-boy' Jones;USA;8.32;Fish;21"
s = {}
(s['id'], s['name'], s['country'], s['average'], s['board'], s['age']) = line.split(";")
I understand that this will take the string line and split it up into each named part, but I don't understand why what I think are keys are being named by using a string, when just a few pages prior, they were named like any other variable, without single quotes.
The purpose of the individual parts is to be searched based on an individual element and then printed on screen. For example, being able to search by ID number and then return the entire thing.
The language in question is Python, if that makes any difference. This is rather confusing for me, since I'm trying to learn this stuff on my own.
My personal best guess is that it doesn't make any difference and that it was personal preference on part of the authors, but it bewilders me that they would suddenly change form like that without it having any meaning, and further bothers me that they don't explain it.
EDIT: So I tried printing the id key both with and without single quotes around the name, and it worked perfectly fine, either way. Therefore, I'd have to assume it's a matter of personal preference, but I still would like some info from someone who actually knows what they're doing as to whether it actually makes a difference, in the long run.
EDIT 2: Apparently, it doesn't make any sense as to how my Python interpreter is actually working with what I've given it, so I made a screen capture of it working https://www.youtube.com/watch?v=52GQJEeSwUA
I don't understand why what I think are keys are being named by using a string, when just a few pages prior, they were named like any other variable, without single quotes
The answer is right there. If there's no quote, mydict[s], then s is a variable, and you look up the key in the dict based on what the value of s is.
If it's a string, then you look up literally that key.
So, in your example s[name] won't work as that would try to access the variable name, which is probably not set.
EDIT: So I tried printing the id key both with and without single
quotes around the name, and it worked perfectly fine, either way.
That's just pure luck... There's a built-in function called id:
>>> id
<built-in function id>
Try another name, and you'll see that it won't work.
Actually, as it turns out, for dictionaries (Python's term for hashes) there is a semantic difference between having the quotes there and not.
For example:
s = {}
s['test'] = 1
s['othertest'] = 2
defines a dictionary called s with two keys, 'test' and 'othertest.' However, if I tried to do this instead:
s = {}
s[test] = 1
I'd get a NameError exception, because this would be looking for an undefined variable called test whose value would be used as the key.
If, then, I were to type this into the Python interpreter:
>>> s = {}
>>> s['test'] = 1
>>> s['othertest'] = 2
>>> test = 'othertest'
>>> print s[test]
2
>>> print s['test']
1
you'll see that using test as a key with no quotes uses the value of that variable to look up the associated entry in the dictionary s.
Edit: Now, the REALLY interesting question is why using s[id] gave you what you expected. The keyword "id" is actually a built-in function in Python that gives you a unique id for an object passed as its argument. What in the world the Python interpreter is doing with the expression s[id] is a total mystery to me.
Edit 2: Watching the OP's Youtube video, it's clear that he's staying consistent when assigning and reading the hash about using id or 'id', so there's no issue with the function id as a hash key somehow magically lining up with 'id' as a hash key. That had me kind of worried for a while.

Writing MySQL databases in Python using mySQLdb

So I have the following code, and it works:
for count in range(0,1000):
L=[random.randint(0, 127),random.randint(0, 127),random.randint(0, 127)]
random.randint(0, 127)
name=''.join(map(chr,L))
number=random.randint(0,1000)
x.execute('insert into testTable set name=(%s), number=(%s)', (name, number))
Above, x is just the cursor I made (obviously). I just create a random string from ASCII values and a random number and write it to my database (this was a purely BS example so that I knew it worked)/
Then,
I have in another script:
x.execute('insert into rooms set \
room_name=(%s),\
room_sqft=(%s),\
room_type=(%s),\
room_purpose=(%s) ,\
room_floor_number=(%s)',
(name, sqft, roomType, room_use_ranking, floor))
And I get a syntax error: invalid syntax on the first line, right at the x. part of x.execute.
What is different between the two lines? In the problem code, all arguments but name are ints (name is a string) that are gotten from a int(raw_input(...)) type prompt that catches bad input errors.
Clearly this works, but what is going wrong in the second piece of code?
Thanks,
nkk
There's a problem on the line BEFORE the x.execute. (x is unexpected at this point). Can you link more of the file?
Also, try this formatting, which can clear up this sort of thing by making the string one blob. (Your syntax highlighter should show it as one big multi-line string, too!)
sql = '''
INSERT INTO rooms
SET room_name=(%s),
room_sqft=(%s),
room_type=(%s),
room_purpose=(%s),
room_floor_number=(%s)
'''
x.execute(sql, (name, sqft, roomType, room_use_ranking, floor))

Categories