I would advise against using eval in 99.99% of all cases. What you could do is use the built-in getattr function:
import sys
var_1 = 10
var_2 = 100
var_3 = 1000
for i in range(1,4):
test_i = getattr(sys.modules[__name__], f"var_{i}") + 1
print(test_i)
Answer from Alexander Ejbekov on Stack OverflowI would advise against using eval in 99.99% of all cases. What you could do is use the built-in getattr function:
import sys
var_1 = 10
var_2 = 100
var_3 = 1000
for i in range(1,4):
test_i = getattr(sys.modules[__name__], f"var_{i}") + 1
print(test_i)
Instead of doing a convoluted naming convention, try to conceive of your problem using a data structure like dictionaries, for example.
var={}
var[1] = 10
var[2] = 100
var[3] = 1000
test={}
for i in range(1,4):
test[i] = var[i] +1
print(test)
If somehow you are given var_1 etc as input, maybe use .split("_") to retrieve the index number and use that as the dictionary keys (they can be strings or values).
Small explanation about using indexing variable names. If you are starting out learning to program, there are many reasons not to use the eval, exec, or getattr methods. Most simply, it is inefficient, not scalable, and is extremely hard to use anywhere else in the script.
I am not one to insist on "best practices" if there is an easier way to do something, but this is something you will want to learn to avoid. We write programs to avoid having to type things like this.
If you are given that var_2 text as a starting point, then I would use string parsing tools to split and convert the string to values and variable names.
By using a dictionary, you can have 1000 non-consecutive variables and simply loop through them or assign new associations. If you are doing an experiment, for example, and call your values tree_1, tree_10 etc, then you will always be stuck typing out the full variable names in your code rather than simply looping through all the entries in a container called tree.
This is a little related to using a bunch of if:else statements to assign values:
# inefficient way -- avoid
if name == 'var_1' then:
test_1=11
elif name == 'var_2' then:
test_2=101
It is so much easier just to say:
test[i]= var[i]+1
and that one line will work for any number of values.
How do I add a prefix/suffix to any given string in python? - Stack Overflow
python - How do I add a suffix to the end of each list element? - Stack Overflow
python - Add comma with Variable name as suffix - Stack Overflow
How to add prefix and suffix to a string in python - Stack Overflow
The name, added_phrase, etc. are coming into the function as variables. But, you are setting them to blanks, which is why you are not seeing any output for print. Also, the return should have the newname you want to send back to the main function, not fix names. Updated code here...
def fix_names(name, position, added_phrase):
# name = ''
# added_phrase = ''
# position = "prefix" or "suffix"
if (position == "prefix"):
prefix = added_phrase
print (added_phrase+' '+name)
newname=added_phrase+' '+name
elif (position == "suffix"):
suffix = added_phrase
print(name+' '+added_phrase)
newname=name+' '+added_phrase
return(newname)
variable = fix_names("John", "prefix", "Dr.")
## Do something else with the new name....
In your function definition, you are overwriting the value of the parameters
name = ''
added_phrase = ''
position = "prefix" or "suffix"
Here is the working code
def fix_names(name, position, added_phrase):
fix_name = added_phrase + name if position == "prefix" else name + added_phrase
return fix_name
op = fix_names("John", "prefix", "Dr.")
print(op)
Here is one way to do it using list comprehension:
['{}_{}'.format(a, b) for b in b_list for a in a_list]
Demo:
>>> a_list = ['mood1', 'mood2', 'mood3', 'dep1', 'dep2', 'dep3']
>>> b_list = ['pre', '6month']
>>> result = ['{}_{}'.format(a, b) for b in b_list for a in a_list]
>>> result
['mood1_pre', 'mood2_pre', 'mood3_pre', 'dep1_pre', 'dep2_pre', 'dep3_pre', 'mood1_6month', 'mood2_6month', 'mood3_6month', 'dep1_6month', 'dep2_6month', 'dep3_6month']
If you are flexible on the ordering of the final list:
from itertools import product, imap
l1 = ['mood1', 'mood2', 'mood3', 'dep1', 'dep2', 'dep3']
l2 = ['pre', '6month']
x = list(imap('_'.join, product(l1, l2)))
This produces ['mood1_pre', 'mood1_6month', ...] rather than ['mood1_pre', 'mood2_pre', ...].
You can concatenate those onto the string using +.
For example (for Python 2):
print "^" + str1 + "$"
Or without + using f-strings in Python 3:
print(f"^{str}$")
Or if you want to add a prefix to every string in a list:
strings = ['hello', 1, 'bye']
decoratedstrings = [f"^{s}$" for s in strings]
result:
['^hello$', '^1$', '^bye$']
Bit out of context but can be helpful for people like me.
If a string list then,
strString = map(lambda x: '^' + x + '$', strString)
The resultant will be string list as well with prefix and suffix added to each string element of the list.
As the title says I want to add a suffix (_2000) to all the 700+ variables in my dataset. I found this tutorial http://www.spss-tutorials.com/suffix-all-variable-names/ . But I don't know how to implement it, as I don't have any background in coding etc. Would you have any tips?
Use locals() to create local variables (apple_df, orange_df, ...)
read_csv = ['apple', 'orange', 'bananna']
for f in read_csv:
locals()[f"{f}_df"] = pd.read_csv(f"{f}.csv")
>>> type(apple_df)
pandas.core.frame.DataFrame
ValueError: Wrong number of items passed 8, placement implies 1
You got that error because you can't assign DataFrame to f variable which is a string in that loop. You have to store it into new variable, for exaple df
df = pd.read_csv(f + '.csv')
If you want to create new variable by f and "_df" you need to use exec
exec(f + "_df" + " = pd.read_csv(f + '.csv')")
It would be better to have a list on the receiving end so that you can do e.g.:
mylist.append(myFun(int))
You can then iterate over the list to get your results.
EDIT
You can also use a dictionary instead of a list so that you can still access your results by name+suffix e.g.:
mydict = {}
for i in range(6): # or whatever your loop looks like
mydict["a_{0}".format(i)] = myFun(int)
I don't see why you would want dynamic variable names, but this should do what you want:
exec("a%s = %s" % (mysuffix, some_other_string));
Replace the second argument by the variable type you need. But most likely you simply want a list of variables.