How to use a string as a part of a variable in python - string

I would like to use a string as a part of the variable in a loop like this:
items = ['apple', 'tomato']
for item in items:
'eat_'+item = open("users/me/"+item+"/file.txt").read()
So that as an output I have 2 variables named eat_apple and eat_tomato.
Obviously, the 'eat_'+item is wrong but to just get my idea.
P.S. I saw similar posts but neither of them helped

Instead of assigning the value to the variable that is a string, you can instead create a dictonary and use the variable name(which is of string type) as key and store a corresponding value to it.
Try it:
items = ['apple', 'tomato']
eat_dict = dict()
for item in items:
eat_dict['eat_'+item] = open("users/me/"+item+"/file.txt").read()

Related

Add single quotes around string in python

I have converted list to string.
but after conversion I am getting string without single quote around the string
for eg:
items = ['aa','bb','cc']
items = ','.join(items)
output is : aa,bb,cc
expected output: 'aa','bb','cc'
You could use a list comprehension to quote the individual strings in the list:
items = ['aa','bb','cc']
items = ','.join([f"'{i}'" for i in items])
print(items) # 'aa','bb','cc'
One way to accomplish this is by passing the list into a string formatter, which will place the outer quotes around each list element. The list is mapped to the formatter, then joined, as you have shown.
For example:
','.join(map("'{}'".format, items))
Output:
"'aa','bb','cc'"

I need an Integer but its a string with a comma

I'm using sqlite3 and trying to get the oid by using the title of the row and then trying to use that oid to update a column in my table.
allOID is a tuple, and when I print it i get this:
>>> <class 'tuple'>
>>> [(1,)]
I'm trying to get the integer out of this tuple but the comma is throwing it off and I can't seem to get it.
Here is all of the code being used currently:
c.execute("""SELECT oid FROM books
WHERE title = :title""",
{
'title': title
})
allOID = c.fetchall()
print(type(allOID[0]))
print(allOID)
c.execute("SELECT * FROM books")
c.execute("""UPDATE books SET
rented = :rented
WHERE oid = :oid""",
{
'rented': rentedVar,
'oid': allOID[0]
})
any help and comments are greatly appreciated!
The comma just indicates that it is a tuple with a single element.
Access it using allOID[0][0].
allOID[0] gets you the tuple out of the list of results, going one level further with allOID[0][0] gets you the first element of the tuple.
For more info, see the docs:
Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective.

groovy iterate through list of key and value

I have this list:
service_name_status=[a-service=INSTALL, b-service=UPGRADE, C-service=UPGRADE, D-service=INSTALL]
And I need to iterate through this list so the first element will be the value of a parameter called "SERVICE_NAME" and the second element will be the value of a parameter called "HELM_COMMAND",
after asserting those values to the parameters I will run my command that uses those parameters and then continue the next items on the list which should replace the values of the parameters with items 3 and 4 and so on.
So what I am looking for is something like that:
def service_name_status=[a-service=INSTALL, b-service=UPGRADE, C-service=UPGRADE, D-service=INSTALL]
def SERVICE_NAME
def HELM_COMMAND
for(x in service_name_status){
SERVICE_NAME=x(0,2,4,6,8...)
HELM_COMMAND=x(1,3,5,7,9...)
println SERVICE_NAME=$SERVICE_NAME
println HELM_COMMAND=$HELM_COMMAND
}
the output should be:
SERVICE_NAME=a-service
HELM_COMMAND=INSTALL
SERVICE_NAME=b-service
HELM_COMMAND=UPGRADE
SERVICE_NAME=c-service
HELM_COMMAND=UPGRADE
SERVICE_NAME=d-service
HELM_COMMAND=INSTALL
and so on...
I couldn't find anything that takes any other element in groovy, any help will be appreciated.
The collection you want is a Map, not a List.
Take note of the quotes in the map, the values are strings so you need the quotes or it won't work. You may have to change that at the source where your data comes from.
I kept your all caps variable names so you will feel at home, but they are not the convention.
Note the list iteration with .each(key, value)
This will work:
Map service_name_status = ['a-service':'INSTALL', 'b-service':'UPGRADE', 'C-service':'UPGRADE', 'D-service':'INSTALL']
service_name_status.each {SERVICE_NAME, HELM_COMMAND ->
println "SERVICE_NAME=${SERVICE_NAME}"
println "HELM_COMMAND=${HELM_COMMAND}"
}
EDIT:
The following can be used to convert that to a map. Be careful, the replaceAll part is fragile and depends on the data to always look the same.
//assuming you can have it in a string like this
String st = "[a-service=INSTALL, b-service=UPGRADE, C-service=UPGRADE, D-service=INSTALL]"
//this part is dependent on format
String mpStr = st.replaceAll(/\[/, "['")
.replaceAll(/=/, "':'")
.replaceAll(/]/, "']")
.replaceAll(/, /, "', '")
println mpStr
//convert the properly formatted string to a map
Map mp = evaluate(mpStr)
assert mp instanceof java.util.LinkedHashMap

Matlab - Define variable from strings [duplicate]

If for instance I have a variable xa=2, and then I construct a string by joining 'x' and 'a', how can I make this new string have the value 2?
xa=2;
var=strcat('x','a');
The result of this is var=xa, but what I want is var=2.
Thank you
Use eval():
var = eval(strcat('x','a'));
It will "evaluate" the string 'xa' and translate it to the value of the variable xa.
Source : MATLAB documentation

Convert a string to array in velocity

I have a velocity variable, like this:
$cur_record.getFieldValue("SelectRoles", $locale)
that is supposed to be an array. If I print its value, (just by putting $cur_record.getFieldValue("SelectRoles", $locale) in the code) i get:
["Accountant","Cashier"]
now, i want to iterate those 2 values, Accountant and Cashier, but it seems to be a String, not an Array, how can i convert that to an array so I can iterate it?..
I have tried to iterate it, but does not work, like this:
#foreach($bla_role in $cur_record.getFieldValue("SelectRoles", $locale))
$bla_role
#end
Also tried to get the value, as if it were an array, does not work either:
$cur_record.getFieldValue("SelectRoles", $locale).get(0)
I've tried setting it to another variable, like this:
#set($roleval = $cur_record.getFieldValue("SelectRoles", $locale))
$roleval.get(0)
but it does not work, but if i set a string, as the value is printed (the value hard coded), it does work!, like this:
#set($roleval = ["Accountant","Cashier"])
$roleval.get(0)
I dont know if I have to escape something, or I am missing something, can some one help me?
thank you!
You're trying to parse a String array that was previously serialized to String.
The following snippet uses substring, split and replace String methods to parse it.
#set($roleval = '["Accountant","Cashier"]')
#set($rolevalLengthMinusOne = $roleval.length() - 1)
#set($roles = $roleval.substring(1, $rolevalLengthMinusOne).split(","))
#foreach($role in $roles)
<h1>$role.replace('"',"")</h1>
#end
At first I tried to use #evaluate to parse it, but I ended up with these String methods.

Resources