Python--逻辑/循环/异常/编码

来源:互联网 发布:excel2003修复软件 编辑:程序博客网 时间:2024/06/06 02:57

1.输入
原始输入,将所输入的东西,不做执行
raw_input()
有执行输入,将执行完的结果返回给变量
input()

2.输出
在3.x版本中,是函数
print()
在2.x版本中:

print a,bprint >>file,a,bprint '%d,%d,%s'%(a,b,c)print "{0}like{1}".format('we','python')pritn "{a}like{b}".format(a='we',b='python')

3.条件语句

ifelifelse#逻辑表达式not/and/or#有一个false,返回false#都是true,返回yx and y#返回第一个true或者falsex or y#三元表达式a=y if x>0 else a=z

4.换行
有括号,自动换行
没有,用反斜线\

5.while/else

break

跳出整个循环

continue

跳出当前循环,进入下一次循环

6.for/else

for x in words:    print '\b'+x,else    print('all done!')

7.去掉字符之间的空格

words=u'你在远方'for x in words:    print x==>你在远方for x in words:    print x,==>你 在 远 方for x in words:    print '\b'+x,==>你在远方

8.列表解析
简介,而且运行速度会比for循环快

l1=['b','c','d','c','a']l2=[][l2.append(i) for i in l1 if not i in l2][(x,y) for x in (1,2,3,4) for y in (10,15,4,5) if x*y>25]

9.异常处理
try/except/finally
有异常之行except
无论是否有异常,都会执行finally

触发异常
raise error(message)
条件触发错误,触发后打印信息
Assert condition,message

try:    a='12'    print(a[7])except Exception,e:    print(e)    print('except')

10.编码
Unicode和UTF8的关系
Unicode只是一个符号集,它只规定了符号的二进制代码,却没有规定这个二进制代码应该如何存储。
UTF-8是Unicode的实现方式之一。

11.编码decode/encode
字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。

decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode(‘gb2312’),表示将gb2312编码的字符串str1转换成unicode编码。

encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode(‘gb2312’),表示将unicode编码的字符串str2转换成gb2312编码。

如果字符串是这样定义:s=u’中文’

则该字符串的编码就被指定为unicode了,即python的内部编码,而与代码文件本身的编码无关。因此,对于这种情况做编码转换,只需要直接使用encode方法将其转换成指定编码即可。

如果一个字符串已经是unicode了,再进行解码则将出错,因此通常要对其编码方式是否为unicode进行判断:

isinstance(s, unicode) #用来判断是否为unicode

用非unicode编码形式的str来encode会报错

0 0