在python中使用参数组装一个长字符串

Omo*_*tis 3 python python-2.7

尝试使用参数在python 2.7中跨多行组合更长的SQL字符串,类似于:

duration_sql = "select MessageTime, " + \
"Value from [%s] " + \
"where Subsystem=%s and " + \
"Field=%s " + \
"and MessageTime > %s and " + \
"MessageTime < %s" % (i, j, k, l, m)
Run Code Online (Sandbox Code Playgroud)

但我得到一个运行时错误:

TypeError: not all arguments converted during string formatting
Run Code Online (Sandbox Code Playgroud)

如果我允许它是一个没有换行符的长字符串,它可以正常工作.我有什么方法可以打破带参数的行的长字符串?无法弄清楚秘密酱......

khe*_*ood 7

试试这个:

duration_sql = ("select MessageTime, "
    "Value from [%s] "
    "where Subsystem=%s and "
    "Field=%s "
    "and MessageTime > %s and "
    "MessageTime < %s") % (i, j, k, l, m)
Run Code Online (Sandbox Code Playgroud)

用括号括起来,你不需要+\组合字符串:所有相邻的字符串文字都合并成一个字符串文字.

(另请参阅Kevin关于不使用字符串格式将变量插入数据库查询的注释.)


Jea*_*bre 5

那是因为%只适用于最后一个字符串:

"MessageTime < %s" % (i, j, k, l, m)
Run Code Online (Sandbox Code Playgroud)

括号你的字符串你会没事的

duration_sql = ("select MessageTime, " + \
"Value from [%s] " + \
"where Subsystem=%s and " + \
"Field=%s " + \
"and MessageTime > %s and " + \
"MessageTime < %s") % (i, j, k, l, m)
Run Code Online (Sandbox Code Playgroud)