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

How do you write a function with multiple lines in a string format?

想写一个函数,这样用的时候可以读成字符串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()

您似乎想使用多行字符串。尝试在字符串的开头和结尾使用三重引号:

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

new_func = """
def do_stuff():
    string = 'strung' #one line
    print(string) #two lines

"""


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

eval(new_code)

function()
do_stuff()

有关可用的其他样式的多行字符串,请参阅此答案:Pythonic way to create a long multi-line string

玩得开心。

您可以按照 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()