Python格式错误(不支持)

时间:2014-05-01 14:16:59

标签: python formatting

我正在使用此方法构建一个字符串。 但由于某种原因,我收到以下错误

ValueError: unsupported format character ''' (0x27) at index 38

我不知道这是从哪里来的。我查了拼写错误但没有。

s = "SELECT %s FROM %s "
data = [colName, tableName]

if whereRoughly:
    s+= "(WHERE "
        for i in range(len(whereRoughly[0])):
            s += "%s LIKE '%%s%' "
            if i+1 < len(whereRoughly[0]): s += "OR "
            data.append(whereRoughly[0][i])
            data.append(whereRoughly[1])
     s+= ")"

s += "ORDER BY %s;"
data.append("desc")

print s
print data
print s % tuple(data)

这里我调用所有上层代码

s.makeSelect(tableName="students", whereRoughly=([1,2], "Wes"))

这是实际输出

SELECT %s FROM %s (WHERE %s LIKE '%%s%' OR %s LIKE '%%s%' )ORDER BY %s;
['*', 'students', 1, 'Wes', 2, 'Wes', 'desc']

1 个答案:

答案 0 :(得分:1)

问题在于:

"'%%s%'"

没有格式代码%',尝试使用它会导致错误。

>>> "'%%s%'" % "foo"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: unsupported format character ''' (0x27) at index 5

我假设您正在尝试获取LIKE之类的SQL '%foo%'语法(由%左右括起来并且单引号。

要使用Python中的旧式%格式来获取格式,您需要转义前导和尾随百分比,如下所示:

>>> "'%%%s%%'" % "foo"
"'%foo%'"

(参见docs.

现代风格string.format

更干净
>>> "'%{0}%'".format('foo')
"'%foo%'"

(另外,上面关于不使用+=构建字符串的评论是有效的 - 更喜欢formatjoin)。