Tricky Python string literals in passing parameter to timeit.Timer() function
Asked Answered
N

2

6

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

Noteworthy answered 22/12, 2008 at 16:25 Comment(0)
W
7

Consider This as an alternative.

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

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.

Witter answered 22/12, 2008 at 16:47 Comment(2)
I tried it and had a SyntaxError: can't assign to literal. Thank you anyway.Noteworthy
The problem was that he put a comma where a semicolon was required. Try it again with what's there now and it should work.Caledonian
B
2

Why bother quoting the strings at all? Just use them directly. ie. change your last line to:

t = timeit.Timer('compare(str1, str2)', "from __main__ import compare, str1, str2")
Boilermaker answered 23/12, 2008 at 1:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.