顺便参数timeit.Timer棘手的Python字符串()函数
-
23-08-2019 - |
题
我有一个困难时期,在Python的timeit.Timer(语句,setup_stmt)建立语句。我感谢所有帮助让我出这个棘手的问题:
所以我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))
我不知道如何逃脱的变量STR1元字符,STR2没有建立语句改变它们的含义:
"from __main__ import compare; p1=%s, p2=%s" % (str1,str2)
我尝试了各种组合,但始终有如下错误: 语法错误:无法分配给字面结果 语法错误:EOL同时扫描单引号字符串结果 语法错误:无效的语法
解决方案
考虑这作为替代。
t = timeit.Timer('compare(p1, p2)', "from __main__ import compare; p1=%r; p2=%r" % (str1,str2))
在%r
使用为字符串,它的Python会引用并正确逸出再版。
编辑:固定码通过改变逗号分号;错误是现在没有了。
其他提示
何苦报价弦呢?只需直接使用它们。 即。你的最后一行更改为:
t = timeit.Timer('compare(str1, str2)', "from __main__ import compare, str1, str2")
不隶属于 StackOverflow