使用函数locals()
>>> for i in range(5): ... locals()['X%s' % i] = '' ... >>> print(X0,X1,X2,X3,X4) >>> print(X5) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'X5' is not defined
还可以生成列表和字典:
>>> X1 0 >>> locals()['X%d' % 1] = [] >>> X1 [] >>> A = [] >>> A [] >>> locals()['X%d' % 1] = {} >>> X1 {}