本文将 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()