簡體   English   中英

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

[英]python - format multiline string with % dictionary

我有一個多行字符串(大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字符串。 我沒有看到traceback因為try / except塊,我從中調用了查詢執行的方法。 故事的道德是:始終在Python 2.x中檢查字符串編碼

“消失”是什么意思? 如果您發出print query ,會返回什么? 看起來你錯過了最后一行的單引號:不應該added = '%(added)s'""" % data

我懷疑你的數據字典丟失了一些關鍵。

例如:

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

KeyError: 'xx'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM