我想写一个函数,这样在使用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()
的任何其他方式来格式化它
最佳答案
您可以按照安德鲁的建议使用 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/