2012-01-25 46 views
0

這裏有三件類似的代碼,前兩個運行良好,最後一個失敗 -Python 2.6 Unicode打印Bug?

# 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 b微克。

或者是?

+2

'item [u'CurrencyID']'的價值是什麼?嘗試打印它的'repr'。 –

+0

嘗試'print('%d)%s%s%s'%...)。encode('utf-8')' –

回答

4

你甚至可能在那裏觸發了一些incosisntency,但實際上,你的代碼 - 在所有的例子中。有點凌亂。

你不應該混合Unicode和非Unicode字符串像

請,故事一看http://www.joelonsoftware.com/articles/Unicode.html - 文章給出了一個什麼Unicode和不同的編碼實際上是一個很好的瞭解,使人們更方便之後編寫任何代碼。至於你的具體代碼片段,如果「item」字典中的所有數據都適合使用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")