I would like to write this:
x = 'something_{}'.format(1) exec('{} = {}'.format(x,np.zeros((2,2)))) Problem: I get SyntaxError: invalid syntax and I don't know how to solve it.
Someone has an idea?
String representation of numpy array is not a valid Python literal, therefore it cannot be evaled.
z = np.zeros((2,2)) str(z) # [[ 0. 0.]\n [ 0. 0.]] <-- invalid literal Technically what you want may be achieved by using repr of object (but in general case it also won't work, e.g. when size of matrix is huge):
import numpy as np x = 'something_{}'.format(1) exec('{} = np.{!r}'.format(x, np.zeros((2,2)))) But what you really want to do is dynamic variable name, and that's a duplicate.
formatcall like this."{} = {}".format(x,np.zeros((2,2)))first to see what its value is. You'll see there's an embedded\n, so you'll get an error passing it toexec().