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))
setup ステートメントでの意味を変更せずに、変数 str1、str2 のメタ文字をエスケープする方法がわかりません。
"from __main__ import compare; p1=%s, p2=%s" % (str1,str2)
さまざまな組み合わせを試しましたが、常に次のエラーが発生します: SyntaxError: can't assign toliteral
SyntaxError
: EOL while scanning single quoted string