我感觉不管是在工作中还是在学习python的时候,都会到处碰壁,这都是很常见的,今天把会在工作中或者学习上的一些技术点总结了一下,希望此篇文章能帮到你度过难题,走出迷雾。再给大家分享之前呢,我介绍一下我弄的一个学习交流群,有什么不懂的问题,都可以在群里踊跃发言,需要啥资料随时在群文件里面获取自己想要的资料。这张学习图就在群里.这个python群就是:643692991 小编期待大家一起进群交流讨论,讲实话还是一个非常适合学习的地方的。各种入门资料啊,进阶资料啊,框架资料啊 爬虫等等,都是有的,风里雨里,小编都在群里等你。
概况
1. 特点:
a) 优雅、明确、简单。
b) 跨平台。
c) 2.x版与3.x版不兼容。
2. 缺点
a) 解释性语言,与c程序相比运行速度慢。
b) 代码不能加密。
3. python解释器
a) cpython:官方版本解释器;使用最广的解释器;使用c语言开发。
b) ipython:基于cpython的交互式解释器,即仅交互增强,执行的python代码功能一样。
c) pypy:采用jit技术,动态编译(非解释执行),执行速度快;与cpython的python代码小部分不同。
d) jython:运行在java平台上的解释器,将python代码编译成java字节码执行。
e) ironpython:运行在.net平台上的解释器,将python代码编译成.net字节码执行。
安装
1. python环境搭建:略。
2. 执行方式
a) 交互式
b) py文件(python命令)
c) py文件(直接执行,仅限linux和mac)
基础
基础语法
1. 注释:“#”开头。
2. 标识符:
a) 首字符必须是字母或下划线;
b) 非首字符可以是字母、数字或下划线;
c) 大小写敏感。
3. 缩进:未规定几个空格或tab,按约定俗成,使用4个空格。
数据类型
1. 整型
a) 范围:任意大小的整数。
b) 十六进制:用0x前缀和0-9、a-f表示。
c) 示例:1、100、-8080、0、0xff00、0xa5b4c3d2。
2. 浮点型
a) 科学计数法:用e表示10。
b) 示例:1.23、3.14、-9.01、12.3e8、1.2e-5。
3. 字符串
a) 范围:以“''”或“”括起来的任意文本。
b) 转义:转义字符“\”,如\n、\t、\\。
c) r:表示字符串不转义。
d) ''':如果字符串含很多换行,使用\n不便阅读,可使用'''化简。
e) 示例
>>> print 'i\'m ok!'i'm ok!>>> print i'm \ok\!i'm ok!>>> print '\\\t\\'\ \>>> print r'\\\t\\'\\\t\\>>> print '''line1... line2... line3'''line1line2line3
4. 布尔值
a) 注意大小写:true、false。
b) 运算符:and、or、not。
5. 空值:none。
变量
以下代码python解释器做了两件事:
str = 'abc'
1. 在内存中创建了一个'abc'的字符串;
2. 在内存中创建了一个名为str的变量,并把它指向'abc'。
常量
1. 常量:常量仍是变量,python无任何机制保证常量不被修改。
2. 约定:常量名全部大写。
3. 示例
pi = 3.14159265359
字符编码
1. 默认编码:ascii(python诞生比unicode发布时间早)。
2. utf-8支持:源文件开头加上。
# -*- coding: utf-8 -*-
3. u:表示字符串使用unicode编码。
>>> print u'中文'中文>>> u'中文'u'\u4e2d\u6587'
4. ord函数
a) 声明
ord(c)
b) 官方说明:given a string of length one, return an integer representing the unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string.
c) 示例
>>> ord('a')65>>> ord(u'中')20013
5. chr函数
chr(i)
b) 官方说明:return a string of one character whose ascii code is the integer i. the argument must be in the range [0..255], inclusive; valueerror will be raised if i is outside that range.
>>> chr(65)'a'
6. unichr函数
unichr(i)
b) 官方说明:return the unicode string of one character whose unicode code is the integer i. the valid range for the argument depends how python was configured – it may be either ucs2 [0..0xffff] or ucs4 [0..0x10ffff]. valueerror is raised otherwise.
>>> unichr(20013)u'\u4e2d'>>> unichr(20013)u'\u4e2d'>>> print unichr(20013)中
7. 编码间转换
a) unicode编码←→utf-8编码
>>> u'abc'.encode('utf-8')'abc'>>> u'中文'.encode('utf-8')'\xe4\xb8\xad\xe6\x96\x87'>>> '\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')u'\u4e2d\u6587'>>> print '\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')中文
b) unicode编码←→gb2312编码
>>> u'中文'.encode('gb2312')'\xd6\xd0\xce\xc4'>>> '\xd6\xd0\xce\xc4'.decode('gb2312')u'\u4e2d\u6587'>>> print '\xd6\xd0\xce\xc4'.decode('gb2312')中文
8. len函数
len(s)
b) 官方说明:return the length (the number of items) of an object. the argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
c) 额外说明:len函数实际调用对象的__len__方法,自定义类可定义该方法,从而使用len函数获取长度。
d) 示例
>>> len(u'abc')3>>> len('abc')3>>> len(u'中文')2>>> len('\xe4\xb8\xad\xe6\x96\x87')6
字符串格式化
1. %运算符:格式化字符串。
2. 占位符
占位符
类型
%d
整数
%f
浮点数
%s
字符串及任意类型
%x
十六进制整数
3. 示例:整数前补空格或0
>>> '%2d-%02d' % (3, 1)' 3-01'
4. 示例:指定浮点数小数位数
>>> '%.2f' % 3.1415926'3.14'
5. 示例:%s支持任意类型
>>> 'age: %s. gender: %s' % (25, true)'age: 25. gender: true'>>> u'hi, %s' % u'michael'u'hi, michael'
6. 示例:%%表示一个%
>>> 'growth rate: %d %%' % 7'growth rate: 7 %'
list
1. list:有序集合;元素类型可不同。
2. 索引
a) 从0开始。
b) -1表示最后1个元素,-2表示倒数第2个元素。
c) 索引越界报错:indexerror: list index out of range。
3. len(list)函数:获取元素个数。
4. list.append(element)函数:末尾追加元素。
5. list.insert(index, element)函数:指定索引位置插入元素。
6. list.pop(index)函数:删除元素,index默认为-1。
7. list[index] = element:索引位置替换为另一元素。
8. 示例
>>> classmates = ['michael', 'bob', 'tracy']>>> classmates[0]'michael'>>> classmates[1]'bob'>>> classmates[-1]'tracy'>>> classmates[-2]'bob'>>> len(classmates)3>>> classmates.append('adam')>>> classmates['michael', 'bob', 'tracy', 'adam']>>> classmates.insert(1, 'jack')>>> classmates['michael', 'jack', 'bob', 'tracy', 'adam']>>> classmates.pop()'adam'>>> classmates['michael', 'jack', 'bob', 'tracy']>>> classmates.pop(1)'jack'>>> classmates['michael', 'bob', 'tracy']>>> classmates[1] = 'sarah'>>> classmates['michael', 'sarah', 'tracy']>>> list0 = ['apple', 123, true]>>> list1 = ['python', 'java', ['asp', 'php'], 'scheme']>>> len(list1)4
9. range函数
range(stop)range(start, stop[, step])
b) 官方说明:this is a versatile function to create lists containing arithmetic progressions. it is most often used in for loops. the arguments must be plain integers. if the step argument is omitted, it defaults to 1. if the start argument is omitted, it defaults to 0. the full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. if step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero (or else valueerror is raised).
>>> range(10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> range(1, 11)[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> range(0, 30, 5)[0, 5, 10, 15, 20, 25]>>> range(0, 10, 3)[0, 3, 6, 9]>>> range(0, -10, -1)[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]>>> range(0)[]>>> range(1, 0)[]
tuple
1. tuple:与list非常类似,但是tuple一旦初始化就不能修改。
2. 函数:除无修改相关的函数外,其他与list一致。
3. 空tuple:用()表示。
4. 1个元素的tuple(特别注意)
a) (element, ):1个元素的tuple。
b) (element):element本身。由于括号()既可以表示tuple,又可以表示括号运算符,为避免歧义,python规定这种情况下,括号()为运算符。
5. 示例
>>> tuple = ('michael', 'bob', 'tracy')>>> len(tuple)3>>> tuple[0]'michael'>>> tuple[-1]'tracy'>>> tuple0 = ()>>> tuple0()>>> string0 = ('python')>>> string0'python'>>> tuple1 = ('python', )>>> tuple1('python',)>>> tuple3 = ('a', 'b', ['a', 'b'])>>> tuple3[2][0] = 'x'>>> tuple3[2][1] = 'y'>>> tuple3('a', 'b', ['x', 'y'])
dict
1. dict:与java的map类似,使用key-value存储,具有极快的查找速度;内部存储顺序与key添加顺序无关;key必须是不可变对象。
2. dict[key]:获取value;如果key不存在,则报错keyerror。
3. dict.get(key, default_value)函数:获取value;如果key不存在,则返回none或指定的默认值。
4. dict[key] = value:添加key-value或覆盖key-value。
5. key in dict:如果dict存在key,则返回true,否则返回false。
6. dict.pop(key)函数:删除key-value。
7. 与list相比,dict特点:
a) 查找和插入的速度极快,不会随着key的增加而增加;
b) 需要占用大量的内存,内存浪费多。
>>> scores = {'michael': 95, 'bob': 75, 'tracy': 85}>>> scores0 = dict(michael=95, bob=75, tracy=85)>>> scores1 = dict([('michael', 95), ('bob', 75), ('tracy', 85)])>>> scores2 = dict({'michael': 95, 'bob': 75, 'tracy': 85})>>> scores == scores0 == scores1 == scores2true>>> scores['adam'] = 67>>> scores['adam']67>>> scores['adam'] = 88>>> scores['adam']88>>> scores['thomas']traceback (most recent call last):file , line 1, in keyerror: 'thomas'>>> 'thomas' in scoresfalse>>> scores.get('thomas')>>> scores.get('thomas', -1)-1>>> scores.pop('bob')75>>> scores{'michael': 95, 'tracy': 85, 'adam': 88}>>> dict0 = {}>>> dict0[(1, 2)] = 1>>> dict0[(1, [2, 3])] = 2traceback (most recent call last):file , line 1, in typeerror: unhashable type: 'list'
set
1. set:与dict类似,但不存储value;由于key不允许重复,所以set无重复key。
2. set.add(element)函数:添加元素;如果是重复元素,则无效果。
3. set.remove(element)函数:删除元素。
4. set0 | set1:并集。
5. set0 & set1:交集。
6. set0 - set1:差集。
7. 示例
>>> set = set([1, 1, 2, 2, 3])>>> setset([1, 2, 3])>>> set.add(4)>>> setset([1, 2, 3, 4])>>> set.add(4)>>> setset([1, 2, 3, 4])>>> set.remove(4)>>> setset([1, 2, 3])>>> set0 = set([1, 2, 3])>>> set1 = set([2, 3, 4])>>> set0 & set1set([2, 3])>>> set0 | set1set([1, 2, 3, 4])>>> set0 - set1set([1])
if语句
1. 完整if语句模板
if : elif : elif : else:
2. 执行过程:当条件判断为true、非零数值、非空字符串、非空list等时,即执行。
>>> age = 3>>> if age >= 18:... print 'adult'... elif age >= 6:... print 'teenager'... else:... print 'kid'... kid
for语句
1. 完整for语句模板
for in :else:
2. 执行过程:循环对象须为collections模块的iterable类型(含next()函数),for语句不断调用循环对象的next()函数取出元素并执行执行1,直到next()函数raise stopiteration或执行1遇到break语句为止;如果由于next()函数raise stopiteration而终止循环,则执行执行2,否则不执行。
3. break和continue语句:与java一致。
4. 示例
>>> for n in [1, 2, 3, 4, 5]:... print n... else:... print 'stopiteration'... 12345stopiteration>>> for n in [1, 2, 3, 4, 5]:... print n... if n > 3:... break... else:... print 'stopiteration'... 1234>>> sum = 0>>> for n in range(101):... sum += n... >>> print sum5050>>> for ch in 'abc':... print ch... abc
while语句
1. 完整while语句模板
while :else:
2. 执行过程:如果条件判断为true、非零数值、非空字符串、非空list等,则不断执行执行1,直到条件判断不成立或遇到break语句为止;如果由于条件判断不成立而终止循环,则执行执行2,否则不执行。
>>> sum = 0>>> while n >> print sum5050
函数
函数定义
1. 函数定义模板
def ():
2. 返回值
a) 如果没有return语句,函数执行完毕后返回none。
b) return none简写为return
>>> def my_abs(x):... if x >= 0:... return x... else:... return -x... >>> my_abs(100)100
空函数
1. 空函数:什么都不做的函数。
2. 空函数模板
def ():pass
3. pass语句
a) 用途:占位符,避免语法错误。
b) 示例(除空函数外)
>>> age = 20>>> if age >= 18:... pass
参数检查
1. 参数个数检查:python解释器自�...