gpt4 book ai didi

python - 如何以字符串格式编写多行函数?

转载 作者:太空宇宙 更新时间:2023-11-04 11:21:50 28 4
gpt4 key购买 nike

想写一个函数,用compile()的时候可以读成字符串,但是函数不止一行,不知道怎么写.

这就是我想尝试写的

def function():
string = "string"
print(string)

new_func = "def function(): string = 'strung' # I don't know how to include the other line here "

new_code = compile(new_func,"",'exec')

eval(new_code)

function()

我想要一种只在一行中编写函数的方法(或任何其他仍然使用 eval()compile() 格式化它的方法)

最佳答案

您可以按照 Andrew 的建议使用 python 多行。相反,如果您想要单行,那么请记住在您的函数字符串中使用\n\t,这样您就不会弄乱缩进。例如:

# normal function definition
#
def function():
string = "string"
print(string)


# multi-line
#
new_func = """
def do_stuff():
string = 'strung' # I don't know how to include the other line here
print(string)"""

# single line, note the presence of \n AND \t
#
new_func2 = "def do_stuff2():\n\tstring = 'strong'\n\tprint(string)\n"

new_code = compile(new_func, "", 'exec')
new_code2 = compile(new_func2, "", 'exec')

eval(new_code)
eval(new_code2)

function()
do_stuff()
do_stuff2()

关于python - 如何以字符串格式编写多行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55820655/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com