英文:
In python: how to convert the input of a function to a string without executing it?
问题
我正在尝试创建一个Python函数,以节省在Jupyter笔记本上编写文档时的时间。而不是逐行在单独的块中编写,我开始将许多行代码写在单个块中。
仅出于格式上的考虑,我想创建一个可以实现此功能的函数:
def printspecial(some_command):
print(f'some_command \t{some_command}')
printspecial(1+1)
# 我想要得到的结果
1+1 2
# 我得到的结果
some_command 2
有人知道如何实现吗?
先谢谢
英文:
I'm trying to make a python function to save time while writing some documentation on jupyter notebook. And instead of writing line by line in separate blocks, I started writing many lines of code in single blocks.
Just for formatting reasons I want to create a function which accomplish this:
def printspecial(some_command):
print(f'some_command \t{some_command}')
printspecial(1+1)
# what I would like to get
1+1 2
# what I get
some_command 2
Does anybody knows how to achieve that?
Thanks in advance
答案1
得分: 3
你可以将printspecial()
传入一个字符串,然后使用eval()
:
def printspecial(some_command):
print("{}\t{}".format(some_command, eval(some_command)))
现在调用printspecial()
并传入一个字符串会得到:
printspecial("1+1")
# 输出
1+1 2
你可以在这里
阅读更多关于eval()
的信息。
请注意,eval()
非常强大,如果被滥用可能会有危险。你可以在这篇文章中了解更多:eval的危险性
。
英文:
You can give printspecial()
a string instead and use eval()
:
def printspecial(some_command):
print("{}\t{}".format(some_command, eval(some_command)))
Now callingprintspecial()
with a string give us:
printspecial("1+1")
#outputs
1+1 2
You can read more on eval()
here
Just note that eval()
is quite powerful and can be dangerous if misused. You can read more about that in this article: The dangers of eval
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论