【问题标题】:Python formatting Error (unsupported) [duplicate]Python格式化错误(不支持)[重复]
【发布时间】:2014-06-18 00:55:24
【问题描述】:

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

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']

【问题讨论】:

  • 另外,你真的,真的不应该在 python 中的字符串上使用+=。您应该正确使用formatjoin 的组合。

标签: python formatting


【解决方案1】:

问题出在这里:

"'%%s%'"

没有格式代码%',尝试使用会出错。

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

我假设您正在尝试获取 SQL LIKE 语法,例如 '%foo%'(两边都用 % 和单引号括起来。

要使用 Python 中的旧式 % 格式获取该格式,您需要像这样转义前导百分比和尾随百分比:

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

(见docs.

这更干净,现代风格string.format

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

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

【讨论】:

    猜你喜欢
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2011-07-14
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多