将参数传递给timeit.Timer()函数时棘手的Python字符串文字

Mar*_*n08 4 python string-literals timeit

我在Python的timeit.Timer(stmt,setup_stmt)中使用setup语句很难.我感谢任何帮助,让我摆脱这个棘手的问题:

所以我的sniplet看起来像这样:

def compare(string1, string2):
    # compare 2 strings

if __name__ = '__main__':
    str1 = "This string has \n several new lines \n in the middle"
    str2 = "This string hasn't any new line, but a single quote ('), in the middle"

    t = timeit.Timer('compare(p1, p2)', "from __main__ import compare; p1=%s, p2=%s" % (str1,str2))
Run Code Online (Sandbox Code Playgroud)

我不知道如何在变量str1,str2中转义元字符而不改变它们在setup语句中的含义:

"from __main__ import compare; p1=%s, p2=%s" % (str1,str2)
Run Code Online (Sandbox Code Playgroud)

我尝试了各种组合,但总是有以下错误:SyntaxError:
扫描单引号字符串时无法分配给文字
语法错误:EOL 语法错误:语法无效

S.L*_*ott 6

考虑这是另一种选择.

t = timeit.Timer('compare(p1, p2)', "from __main__ import compare; p1=%r; p2=%r" % (str1,str2))
Run Code Online (Sandbox Code Playgroud)

%r使用的字符串,它是由Python会引用正确逃脱再版.

编辑:修改代码通过将逗号更改为分号; 错误现在消失了.