python - 用%字典格式化多行字符串

3 投票
2 回答
2907 浏览
提问于 2025-04-17 12:45

我有一个多行字符串(一个很大的 MySQL 查询),我想用字典(数据)来格式化它,像这样:

query = """
        INSERT LOW_PRIORITY INTO goods(id, type, volume, strength,
        country, price, description, year, image, url, class, color,
        grape, vintage, dryness, shop, added)
        VALUES (
        '%(id)s',
        '%(type)s',
        '%(volume)s',
        %(strength)d,
        '%(country)s',
        %(price)d,
        '%(description)s',
        '%(year)s',
        '%(image)s',
        '%(url)s',
        '%(class)s',
        '%(color)s',
        '%(grape)s',
        %(vintage)d,
        '%(dryness)s',
        '%(shop)s',
        '%(added)s'
        ) ON DUPLICATE KEY UPDATE
        type = '%(type)s',
        volume = '%(volume)s',
        strength = %(strength)d,
        country = '%(country)s',
        price = %(price)d,
        description = '%(description)s',
        year = '%(year)s',
        image = '%(image)s',
        url = '%(url)s',
        class = '%(class)s',
        color = '%(color)s',
        grape = '%(grape)s',
        vintage = %(vintage)d,
        dryness = '%(dryness)s',
        shop = '%(shop)s',
        added = '%(added)s""" % data

当我尝试这样做的时候,没有出现任何错误,但我的字符串却消失了。有没有办法解决这个问题呢?

更新:我找到了问题所在。我试图用字典的 Unicode 值来格式化 ASCII 字符串。我没有看到错误信息,因为有一个 try/except 块,这个块里调用了我的查询执行方法。这个故事的教训是:在 Python 2.x 中,始终检查字符串编码。

2 个回答

0

我怀疑你的数据字典里缺少了一些关键的内容。

比如说:

In [1]: "%(xx)s" % dict()
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/<redacted>/<ipython-input-1-475612d1eaa2> in <module>()
----> 1 "%(xx)s" % dict()

KeyError: 'xx'
0

你说的“消失”是什么意思?如果你执行 print query,会返回什么?看起来你在最后一行漏掉了一个单引号:应该是 added = '%(added)s'""" % data 吧。

撰写回答