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

标签 python string eval

我想写一个函数,这样在使用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/

相关文章:

python - scipy.optimize.minimize -- 当一个是 numpy 数组时如何指定边界

c - 如何在用户按下 C 中的特定键之前读取字符串?

java - 字符串数组如何存储数组?

javascript - 在 Javascript 中创建一个可以访问局部变量的类

bash - 检查具有动态名称的 Bash 变量

javascript - VUE引擎如何评估属性代码?

python - 使用 numpy 进行数组广播

python - 将参数传递到 AWS CLI 命令

python - 仅针对特定列禁用 pandas read_csv 中的默认 na 解析

c - 在 C 中替换字符串中的字符并随后取消替换的最佳方法