将参数传递给 timeit.Timer() 函数的棘手 Python 字符串文字
我在 Python 的 timeit.Timer(stmt, setup_stmt) 中的 setup 语句上遇到了困难。 我很感谢任何帮助我摆脱这个棘手问题的帮助:
所以我的片段看起来像这样:
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
语法错误:语法无效
I'm having a hard time with the setup statement in Python's timeit.Timer(stmt, setup_stmt). I appreciate any help to get me out of this tricky problem:
So my sniplet looks like this:
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))
I don't know how to escape the metacharacter in the variable str1, str2 without changing their meaning in the setup statement:
"from __main__ import compare; p1=%s, p2=%s" % (str1,str2)
I tried various combination but always have the following errors:
SyntaxError: can't assign to literal
SyntaxError: EOL while scanning single-quoted string
SyntaxError: invalid syntax
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将此视为替代方案。
%r
使用字符串的 repr,Python 总是正确地引用和转义该字符串。编辑:通过将逗号更改为分号来修复代码; 错误现在消失了。
Consider This as an alternative.
The
%r
uses the repr for the string, which Python always quotes and escapes correctly.EDIT: Fixed code by changing a comma to a semicolon; the error is now gone.
为什么要费心引用字符串呢? 直接使用它们即可。
IE。 将最后一行更改为:
Why bother quoting the strings at all? Just use them directly.
ie. change your last line to: