python 列表(list)元組(tuple)字典(dict)如何打印中文總結

python中,如果直接使用print去打印含中文元素的list、tuple、dict,並不能打印出中文字符,而是打印出unicode編碼,

例如:

tuple1 = ('小甲魚', '耐克', '李寧', '香奈兒')
print tuple1
直接輸出的結果:
('\xe5\xb0\x8f\xe7\x94\xb2\xe9\xb1\xbc', '\xe8\x80\x90\xe5\x85\x8b', '\xe6\x9d\x8e\xe5\xae\x81', '\xe9\xa6\x99\xe5\xa5\x88\xe5\x84\xbf')


元組,如何打印出中文呢?

#方法一:打印元組可以用格式化處理
tuple1 = ('小甲魚', '耐克', '李寧', '香奈兒')
lstring = ''
for item in tuple1:
    if tuple1[-1] == item:
        lstring += '%s' % item
    else:
        lstring += '%s, ' % item
print lstring
運行結果:
小甲魚, 耐克, 李寧, 香奈兒


#方法二循環遍歷,再打印出來
tuple1 = ('小甲魚', '耐克', '李寧', '香奈兒')
i = 0
lstring = ''
for item in tuple1:
    if i < (len(tuple1)-1):
        lstring = lstring + item + ', '
    else:
        lstring = lstring + item
    i += 1
print lstring

運行結果:
小甲魚, 耐克, 李寧, 香奈兒

#方法三直接去掉轉義字符\,然後打印出來
lstring = str(tuple1).decode('string_escape')
print lstring
運行結果:
('小甲魚', '耐克', '李寧', '香奈兒')


字典,也可以按上述方式打印:

dict6 = {1:'淘寶', 2:'京東', 3:'天貓', 4:'1號店', 5:'美團'}

#方法一:使用格式化打印字典數據
dstring1 = ''
for eachKeys in dict6.keys():
    fill = '(%s : %s)' % (eachKeys, dict6[eachKeys])
    dstring1 += fill
    if dict6.keys().index(eachKeys) + 1 != len(dict6):
        dstring1 += ','

print dstring1

#方法二:非格式化打印字典數據,數據沒有保存到字符串中
i = 0
string1 = ''
for eachKeys in dict6.keys():
    if i < (len(dict6)-1):
        print ('(' + str(eachKeys) + ' : ' + dict6[eachKeys] + '),'),
        i += 1
    else:
        print ('(' + str(eachKeys) + ': ' + dict6[eachKeys] + ')')

#方法三:方法二微調,把數據保存到字符串中
i = 0
string1 = ''
for eachKeys in dict6.keys():
    if i < (len(dict6)-1):
        fill = '(' + str(eachKeys) + ' : ' + dict6[eachKeys] + '),'
        string1 += fill
        i += 1
    else:
        fill = '(' + str(eachKeys) + ' : ' + dict6[eachKeys] + ')'
        string1 += fill
print string1

#方法四:直接去掉轉義字符\,然後打印出來
lstring = str(dict6).decode('string_escape')
print lstring
輸入結果:
(1 : 淘寶),(2 : 京東),(3 : 天貓),(4 : 1號店),(5 : 美團)
(1 : 淘寶), (2 : 京東), (3 : 天貓), (4 : 1號店), (5: 美團)
(1 : 淘寶),(2 : 京東),(3 : 天貓),(4 : 1號店),(5 : 美團)
{1: '淘寶', 2: '京東', 3: '天貓', 4: '1號店', 5: '美團'}

最後一個方法是最簡單,而且可以原樣打印出來~~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章