I am wondering if there is a way to use from string from lxml while including a variable ? For example, in my code :
new_elem = etree.fromstring("""<asl abortExpression="" elseExpression=""")
But, if I had a variable
x = "Tag"
and I wanted to add this variable to my fromstring parameter as '+x', is there a way to do this so it's
new_elem = etree.fromstring("""<asl abortExpression="" elseExpression=""" + x)
Related
I am trying to create a function named make_string, that uses * correctly with a parameter: strings
The function should return a string of all the values supplied joined, and separated by a space.
Outside the make_string function, I declare a variable named my_string, and assign the value returned from the make_string function.
Then I call the make_string function with the following values: "Alderaan", "Coruscant", "Dagobah", "Endor", "Hoth". Finally I print the value of my_string to the terminal...and it returns None, when it should return Alderaan Coruscant Dagobah Endor Hoth
Can anybody tell me where I am going wrong please?
def make_string(*strings):
my_string = ""
for x in strings:
my_string = x.join(strings)
return my_string
my_string = make_string()
make_string("Alderaan", "Coruscant", "Dagobah", "Endor", "Hoth")
print(my_string)
There are a few things going on in your code that are a little wonky.
You're constantly re-assigning the value of my_string every time you loop through for x in strings
There's no reason to start with a blank string here since you're already using join
Your function call isn't setting to my_string -- it isn't set to anything. What you want is like my_string = make_string("Bob", "Mary") etc.
This should do the trick:
def make_string(*strings):
return " ".join(strings)
my_string = make_string("Alderaan", "Coruscant", "Dagobah", "Endor", "Hoth")
print(my_string)
Personally, I would say you don't even need a function here, especially if you can easily set what you're using for *strings to a variable. For example:
planets = ["Alderaan", "Coruscant", "Dagobah", "Endor", "Hoth"]
print(" ".join(planets))
I'm looking for a shorter but still clean and flexible way to write what I have below.
Variable to work with (length varying)
drpfile_exportname = '1911_CocaCola_XMasNow_TVC30sec_03_Roughcut_Tv10_PV01_Ov01_200319_prev_for_approval_H264'
Long way of doing it but clean
# Split string by "_"
drpfile_exportname_list = drpfile_exportname.split("_")
# Set variables
ul_date = drpfile_exportname_list[0]
up_client = drpfile_exportname_list[1]
up_cprojname = drpfile_exportname_list[2]
# Join variables to create desired name
upload_projname = "_".join((ul_date, up_client, up_cprojname))
Alternative oneliner not so flexible as no variables are assigned and in my opinion not a beautiful way to solve it
upload_projname = ("_".join(drpfile_exportname.split('_')[0:3]))
Thought something like this would work but always had problems with it
ul_date, up_client, up_cprojname = drpfile_exportname.split('_', 2)
Print:
print("\nProject name: {}".format(upload_projname))
Result that should be stored in a variable:
Project name: 1911_CocaCola_XMasNow
You can slice the result of split.
ul_date, up_client, up_cprojname = drpfile_exportname.split('_')[:3]
Or you can assign a dummy variable to the part you want to ignore
ul_date, up_client, up_cprojname, *_ = drpfile_exportname.split('_')
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 5 years ago.
I have a list of commands that I want to iterate over so I've put those commands into a list. However, I want to also use that list as strings to name some files. How do I convert variable names to strings?
itemIDScore = """SELECT * from anytime;"""
queryList = [itemIDScore, accountScore, itemWithIssue, itemsPerService]
for x in queryList:
fileName = x+".txt"
cur.execute(x) #This should execute the SQL command
print fileName #This should return "itemIDScore.txt"
I want fileName to be "itemIDScore.txt" but itemIDScore in queryList is a SQL query that I'll use elsewhere. I need to name files after the name of the query.
Thanks!
I don't think you may get name of the variable as string from the variable object. But instead, you may create the list of string of your variables as:
queryList = ['itemIDScore', 'accountScore', 'itemWithIssue', 'itemsPerService']
Then you may access the value of variable from the variable name string using the globals() function as:
for x in queryList:
fileName = "{}.txt".format(x)
data = globals()[x]
cur.execute(data)
As the globals() document say:
Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).
As far as I know, there is no easy way to do that, but you could simply use a dict with what currently are variable names as keys, e.g.:
queries = {
'itemIDScore': 'sql 1',
'accountScore': 'sql 2',
...
}
for x in queries:
fileName = x + ".txt"
cur.execute(queries[x])
print fileName
This would also preserve your desired semantics without making the code less readable.
I think you would have an easier time storing the names explicitly, then evaluating them to get their values. For example, consider something like:
itemIDScore = "some-long-query-here"
# etc.
queryDict = dict( (name,eval(name)) for name in ['itemIDScore', 'accountScore', 'itemWithIssue', 'itemsPerService'] )
for k in queryDict:
fileName = k+".txt"
cur.execute(queryDict[k])
You can use the in-built str() function.
for x in queryList:
fileName = str(x) + ".txt"
cur.execute(x)
This may be a very simple question, but how can I use a string for the name of a class/object declaration? I'm working with PySide, and I have code that will make a text input for every entry in an array.
i=0
d = {}
for name in mtlName:
i = i+1
curOldLabel = d["self.oldLabel" + str(i)]
So now I have to just decalre QtGui.QLineEdit() as what curOldLabel equals (self.oldLabel1 = QtGui.QLineEdit(), self.oldLabel2 = QtGui.QLineEdit(), etc). How do I tell it not to overwrite curOldLabel, but instead use the string as the name for this object?
Your best bet is to use another dictionary to store those objects. It's safe, it's easy to use and it has fast lookup. You don't want to be creating normal variables with dynamic names in most scenarios.
I have a group of variables named k1, k2 k3....k52. They variables are lists/numpy arrays depending on the scenario. Essentially I'd like to perform the same manipulation on them en masse within a loop, but am having trouble ierating over them. Essentially what i'd like is something like this:
for i in arange(0,52):
'k'+ str(i) = log10(eval('k' + str(i)))
Obviously i know the above wont work, but it gives the idea. My actual attempt is this:
for i in arange(0,10):
rate = eval('k' + str(i))
rate = np.array(rate,dtype=float)
rate = log10(rate)
rate.tolist()
vars()[rate] = 'k' + str(i)
(Its changed to a numpy array so i can log it, and then back to a list so i change the variable name back to what it was) Thanks for any help you can provide. I get the feeling this is something quite simple, but its escaping me at the moment.
edit: thanks very much for the answers, i should have explained that I can't really store them a set array, they need to remain as independent variables for reasons i don't really want to go into.
The line:
vars()[rate] = 'k' + str(i)
has to be replaced by:
vars()['k' + str(i)]=rate
If the items are all globals you can use the globals() call to get a mapping, then manipulate them:
g = globals()
for i in arange(0,52):
varname = 'k{}'.format(i)
g[varname] = log10(g[varname])
but you really want to just store all those items in a list or dictionary instead.