Tricky Python String Literals Passing the Timeit.Timer () Parameter

It is difficult for me with the installation instruction in Python timeit.Timer (stmt, setup_stmt). I appreciate any help to save me from this difficult 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 do not know how to avoid the metacharacter in the variable str1, str2 without changing their value in the installation statement:

 "from __main__ import compare; p1=%s, p2=%s" % (str1,str2) 

I tried a different combination, but always had the following errors: Syntax Error: cannot assign literal
SyntaxError: EOL when scanning a one-line string
Syntax Error: invalid syntax

+4
source share
2 answers

Consider this as an alternative.

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

%r uses an expression for the string, which Python always quotes and escapes correctly.

EDIT: fixed code, changing the comma to semicolon; the error has disappeared.

+6
source

Why quote strings at all? Just use them directly. i.e. change your last line to:

 t = timeit.Timer('compare(str1, str2)', "from __main__ import compare, str1, str2") 
+2
source

All Articles