1. 使用`globals()`函数:
var_name = 'new_variable'
globals()[var_name] = 'Hello, World!'
print(new_variable) 输出:Hello, World!
2. 使用`setattr()`函数:
class Test: pass
var_name = 'new_variable'
setattr(Test, var_name, 'Hello, World!')
obj = Test()
print(obj.new_variable) 输出:Hello, World!
3. 使用`eval()`函数:
out_params = 'count'
print(eval(out_params)) 输出:4
4. 使用`locals()`或`vars()`函数:
var = 'This is a string'
varName = 'var'
s = locals()[varName]
s2 = vars()[varName]
print(s) 输出:This is a string
print(s2) 输出:This is a string
5. 使用`exec()`函数:
exec('j = 0')
print(globals()['j']) 输出:0
6. 使用`format()`函数进行字符串格式化:
var = 'world'
message = 'Hello, {}!'.format(var)
print(message) 输出:Hello, world!
请注意,使用`eval()`和`exec()`函数可能存在安全风险,因为它们可以执行任意代码。因此,在实际应用中,请确保你信任传递给这些函数的字符串内容。