我想编写一个函数,所以当使用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()
看起来你想使用多行字符串。在字符串的开头和结尾处尝试三重引号:
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
玩得开心。