【问题标题】:Python 2.6 Unicode Print Bug?Python 2.6 Unicode 打印错误?
【发布时间】:2012-01-25 11:59:39
【问题描述】:

这里有三段类似的代码,前两段运行正常,最后一段失败--

    # 1
    print '%d) "%s" ' % (new_item_count, item[u'Title'].encode('utf-8')),
    print '%s' % item[u'CurrencyID'],
    print '%s !' % item[u'Value']

    # 2
    print '%d) "%s" %s%s !!' % (new_item_count,
            item[u'Title'].encode('utf-8'),
            item[u'CurrencyID'].encode('utf-8'),
            item[u'Value'])

    # 3
    print '%d) "%s" %s%s !!!' % (new_item_count,
            item[u'Title'].encode('utf-8'),
            item[u'CurrencyID'],
            item[u'Value'])

输出(注意末尾有区别的感叹号)--

37) "HP Pavilion Laptop / Intel® Core™ i3 Processor"  USD 510.0 !
37) "HP Pavilion Laptop / Intel® Core™ i3 Processor" USD510.0 !!
'ascii' codec can't decode byte 0xc2 in position 29: ordinal not in range(128)

这是在 Python 2.6.5 下(Ubuntu 10.04 软件包,32 位和 64 位的行为相同)--

$ python -V
Python 2.6.5
$ uname -a
Linux <> 2.6.39.1-x86_64-<> #1 SMP Tue Jun 21 10:04:20 EDT 2011 x86_64 GNU/Linux

我能想到的唯一解释是这是一个 Python 错误。

是吗?

【问题讨论】:

  • item[u'CurrencyID'] 的值是多少?尝试打印其repr
  • 试试print('%d) %s %s%s' % ...).encode('utf-8')

标签: python unicode ubuntu-10.04


【解决方案1】:

您甚至可能在其中触发了一些不一致,但实际上,您的代码 - 在所有示例中。有点乱。

您不应该像这样混合使用 unicode 和非 unicode 字符串

请看一下http://www.joelonsoftware.com/articles/Unicode.html - 这篇文章让人们很好地理解了 unicode 和不同的编码实际上是什么,并让之后的编码变得更加容易。

至于您的特定 sn-p,如果您在“项目”字典中的所有数据都在 unicode 中适当,如它所见,只需在 unicode 中进行字符串插值,并将最终结果字符串编码为预期的输出格式:

message = u'%d) "%s" %s%s !!!' % (new_item_count,
            item[u'Title'],
            item[u'CurrencyID'],
            item[u'Value']))
print message.encode("utf-8")

【讨论】: