首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >可以从字符串运行python变量声明吗?

可以从字符串运行python变量声明吗?
EN

Stack Overflow用户
提问于 2018-07-25 08:14:34
回答 1查看 63关注 0票数 0

这就是我要找的行为。

代码语言:javascript
复制
"a = 2" # execute this line
print a
> 2

我知道exec语句,但我需要它在Python2和3中工作,而Python3不允许exec创建局部变量。有没有别的办法来解决这个问题呢?

编辑:就像我说的--我知道我不能使用exec,假设重复的答案是使用exec

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-25 08:31:29

我不一定认为这是个好主意……

代码语言:javascript
复制
import ast
def parse_assignment(s):
    lhs,rhs = s.split("=",1)
    globals()[lhs] = ast.literal_eval(rhs)

parse_assignment("hello=5")
print(hello)
parse_assignment("hello2='words'")
print(hello2)
parse_assignment("hello3=[1,'hello']")
print(hello3)

https://repl.it/repls/BiodegradableLiveProgrammer

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51509206

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档