Python字符串编码
在Python中有些特殊的地方是存在两种字符串,分别为str和unicode字符串,他们都继承自basestring。
如:s="hello world",s为str;us=u"hello world",us为unicode。
使用help(str)和help(unicode)可以查看各自说明,他们都有decode、encode方法,
decode用于将str字符串解码为unicode字符串,
encode用于将unicode字符串编码为str字符串。
在指定编码如下时有
#-*- encoding: UTF-8 -*-
示例解析:
>>> s='hello 世界' //s为str类型,utf-8编码
>>> dutf8=s.decode('gbk') //与源编码不符,用gbk解码会出错
>>> dgbk=s.decode('utf-8') //解码正确
>>> us=dgbk.encode('gbk') //编码转换正确,us为utf-8编码
总结:
1、unicode编码为中转编码,编码顺序为:
decode encode
str (utf-8编码) ------> unicode ------> str(gbk编码或者其他编码)
2、要显示汉字必须用unicode编码途径有二
1. s.decode("utf-8")
2. u"字符串"
3、由上可知,要想转码正确,首先必须知道转换对象的正确编码。
相关文档:
client:
import socket, sys
if __name__ == '__main__':
#处理参数
argv = sys.argv
if (len(argv)!=3) or (len(argv)==2 and argv[1]=='/?'):
print '>>>Useage:', argv[0], '<address> < ......
#coding=utf-8
from newtest.wiki.models import WiKi
from django.template import loader, Context
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
def index(request, pagename=""):
"""显示正常页面,对页面的文字做特殊的链接处理"""
......
来CSDN的时候,刚刚接触Python,那时候对Python的嵌入部分很感兴趣,只是一直没有时间来弄清其面纱,因此也一直没有使用嵌入的功能,另一个原因是我还没有真正用Python写过一个正式的有用点的东西,不过,现在回过头来继续看这一部分,发现还是挺简单的。以前想把这部分翻译出来,可是由于时间原因,也没有那精力,所以这里 ......
http://blog.chinaunix.net/u1/59571/showart_1901962.html
1. 在Python中使用中文
在Python中有两种默认的字符串:str和unicode。在Python中一定要注意区分“Unicode字符串”和“unicode对象”的区别。后面所有的“unicode字符串”指的都是pyt ......