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: ‘美团‘}最后一个方法是最简单,而且可以原样打印出来~~~
python 列表(list)元组(tuple)字典(dict)如何打印中文总结
原文:http://lynnpaul.blog.51cto.com/6803462/1837197