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、由上可知,要想转码正确,首先必须知道转换对象的正确编码。
相关文档:
#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=""):
"""显示正常页面,对页面的文字做特殊的链接处理"""
......
import sys
import os
import datetime
import time
class ArgsDealwith:
def arg_environment(self, args):
filepath = ('PYTHON_PATH', 'path')
for i in filepath:
&nbs ......
在讲述filter,map和reduce之前,首先介绍一下匿名函数lambda。
lambda的使用方法如下:lambda [arg1[,arg2,arg3,...,argn]] : expression
例如:
>>> add = lambda x,y : x + y
>>> add ......
Python中的文件操作以及输入输出
我们可以分别使用raw_input和print语句来完成这些功能。对于输出,你也可以使用多种多样的str(字符串)类。例如,你能够使用rjust方法来得到一个按一定宽度右对齐的字符串。利用help(str)获得更多详情。
另一个常用的输入/输出类型是处理文件。创建、读和写文件的能力是 ......
Python中的异常
当你的程序中出现某些异常的状况的时候,异常就发生了。
一.处理异常
我们可以使用try..except语句来处理异常。我们把通常的语句放在try-块中,而把我们的错误处理语句放在except-块中。
例如:
#!/usr/bin/python
# Filename: try_except.py
import sys
try:
s = raw_input('E ......