将函数的输入转换为字符串而不执行它?

huangapple go评论69阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年4月20日 02:40:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76057855.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定