Python代码的中文乱码问题小结

本文将 python 的中文问题大概写一下
本人所用的Python版本为2.7

我在windows下使用 vim 编写 python 程序
将vim 的中文中配置为gbk
即 将vim 的目录中的 _vimrc 文件中加入中文编码

set fileencodings=gbk,utf-8,ucs-bom,default,latin1

【】print 字符串的中文问题

在 py 文件开头加上

#encoding=gbk

print 的乱码就可以解决了

【】序列、列表、元组内容中的中文问题

但是列表的中文仍然有问题
在中文字符后面加上

decode('string_escape')

示例代码如下:

#encoding=gbk

shoplist=["苹果","梨","香蕉","桃子","樱桃"]
print "我一共买了",len(shoplist),"种水果"
print "这些水果是"
for s in shoplist:
  print s,
print "我也买了杏"
shoplist.append("杏")
print "我现在买的是",str(shoplist).decode('string_escape')
shoplist.sort()
print "排序后买的是",str(shoplist).decode('string_escape')

olditem=shoplist[0]
print "第一种我买的是",olditem

del(shoplist[0])
print "我后来又买了",str(shoplist).decode('string_escape')

【】Tkinter 的中文问题

Tkinter 的GUI界面如果使用中文,也会出现乱码
需要在中文字符后面加上

decode('gbk')

示例代码如下

#encoding=gbk 
from Tkinter import *

class App:
  def __init__(self,master):
    frame=Frame(master)
    frame.pack()
    self.button=Button(frame,text="退出".decode('gbk'),fg="red",command=frame.quit)
    self.button.pack(side=LEFT)
    self.hi_there=Button(frame,text="你好".decode('gbk'),fg="blue",command=self.say_hi)
    self.hi_there.pack(side=LEFT)
  def say_hi(self):
    print "嘿,你好各位!"

root=Tk()
app=App(root)

root.mainloop()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值