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、由上可知,要想转码正确,首先必须知道转换对象的正确编码。
相关文档:
Python lists have a built-in sort() method that modifies the list in-place and a sorted() built-in function that builds a new sorted list from an iterable.
There are many ways to use them to sort data and there doesn't appear to be a single, central place in the various man ......
Python中可以使用装饰器对函数进行装饰(或说包装),利用这个特性,可以很方便、简洁地解决一些问题,比如获得函数执行时间的问题。
首先,我们定义一个函数,如下:
def exeTime(func):
def newFunc(*args, **args2):
t0 = time.time()
print "@%s, {%s} start" % (time.strftime("%X", time.local ......
模块
一.简介
模块基本上就是一个包含了所有你定义的函数和变量的文件。为了在其他程序中重用模块,模块的文件名必须以.py为扩展名。
例如:
#!/usr/bin/python
# Filename: using_sys.py
import sys
print 'The command line arguments are:'
for i in sys.argv:
print i
print '\n ......
Python中的异常
当你的程序中出现某些异常的状况的时候,异常就发生了。
一.处理异常
我们可以使用try..except语句来处理异常。我们把通常的语句放在try-块中,而把我们的错误处理语句放在except-块中。
例如:
#!/usr/bin/python
# Filename: try_except.py
import sys
try:
s = raw_input('E ......
Python基础(chapter3)
1 setence and syntax语句和语法
1.1 #为注释符号
1.2 \n是标准行分隔符, 通常一个语句一行
1.3 反斜线\表示下一行继续, 用来将单条语句放入多行…尽量使用括号代替
1.4 分号;表示将两个语句连接在一行中…不提倡
1.5 冒号:表示将代码块的头和体分开
1.6 语句(代码块)用缩进块方式 ......