Python SyntaxError: cannot assign to operator – Defining variables as sum of strings in for loop

Question:

I’m trying to condense some repetitive code by setting up a for loop to define variable names. I get that python doesn’t like having operators on the left side of equations, but are there any workarounds for adding strings together for the sake of defining a variable name that will later be referenced?

cases     = ['case1','case2', 'case3']
condition = ['con1', 'con2']
var       = ['var1', 'var2', 'var3']
for i in cases :
    for j in condition :
        for k in var :
            filename = i+j+k+'.txt'
            i+j+k = np.loadtxt(filename)
            plt.plot(x, i+j+k)
plt.show

I’m thinking my best option would option would be set up a matrix in the loop as

value[i,j,k] = np.loadtxt(filename)
plt.plot(x, value[i,j,k])

but that might lead to bigger headaches in the future so I’m trying to avoid if possible.

Asked By: jtolento

||

Answers:

Creating variable names based on strings is not allowed. Using a dictionary to store the values with your custom string is the closest thing you will get.

Also, you have a mistake here: filename = i+j+k'.txt' , you need to add the .txt string to the other strings like this filename = i+j+k+'.txt'

cases     = ['case1','case2', 'case3']
condition = ['con1', 'con2']
var       = ['var1', 'var2', 'var3']
case_condition_variables = dict()

for i in cases :
    for j in condition :
        for k in var :
            filename = i+j+k+'.txt'
            case_condition_variables[i+j+k] = np.loadtxt(filename)
            plt.plot(x, case_condition_variables[i+j+k])

print(case_condition_variables) # will show you all the name - value pairs
Answered By: JRose

You are making this infinitely more complex then necessary. You don’t need to create a variable name from strings. Instead, just use a fixed variable:

            data = np.loadtxt(filename)
            plt.plot(x, data)

On the other hand, you can build a filename from strings:

filename = i + j + k + '.txt'

The only thing you are missing here is the + to correctly concatenate the '.txt' extension to the filename.

Answered By: Code-Apprentice
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.