python2 笔记

***************************************
【Python 应用笔记 THINKCORE】
***************************************
AT+CIPSTART="TCP","47.93.59.179",6001
AT+CWJAP="Pcroom","123456789"
zipimport.ZipImportError: can't decompress data; zlib not available
1环境 :yum install readline-devel 安装命令解析

baudrate sync fail ... retry...

GET /devices/5835707 HTTP/1.1api-key: xUrvOCDB=iRuS5noq9FsKrvoW=s=Host:api.heclouds.com\r\n\r\n

AT+CIPSTART="TCP","183.230.40.33",80

【Python 环境搭建】

 

【变量 对象 分开 】

变量名自身也在内存中
数值也在内存中

变量指向 内存的数值

内存回收 对象引用计数为0
"=" 用于将变量与内存中的某对象绑定 。 如果事先存在 直接进行绑定
否则 则由 “=” 创建引用对象、
test =“too”
vo =“too”
In [21]: id(test)
Out[21]: 46695216

In [22]: id(vo)
Out[22]: 46695216
##############################################################
变量命名规则:

变量名 没有类型 对象才有
变量可以引用任何对象


【数据结构 】
[1,2,3,3,4] ['sfdsf','2322','12'] 列表

列表可变对象 : 可以修改 元素修改 (地址变)
In [1]: l1 = ["thin","is","thinkcore"]
In [2]: print l1
['thin', 'is', 'thinkcore']
In [3]: l1[2] = "yoot"
In [4]: print l1
['thin', 'is', 'yoot']
(1,3,2,4,5) ('12','23','2323'); 元祖

元祖 不可标对象


切片
In [8]: name = 'jeer'

In [9]: name[0]
Out[9]: 'j'

In [10]: name[2:]
Out[10]: 'er'

In [11]: name[0:4:2]
Out[11]: 'je'

映射 : 字典

d = {'key':121,'key1';1221}
d['key']

 

 

可变对象 元组是不可变序列

len(name) 获取长度。

is 左右引用对象是不是一样 TURE
In [1]: name ="11"
In [2]: boot="11"
In [3]: name is boot
Out[3]: True
In [4]: type(name) is type(boot)
Out[4]: True

控制流:

if botlweew1:
sdfud1

elif fdsafs2:
dsfs

else _suite

try 异常捕获



输入 :
rgw_input
input
In [1]: raw_input("plz input a num:")
plz input a num:dsffds
Out[1]: 'dsffds'
In [4]: a = raw_input("put intput a :")
put intput a thin is a data

In [5]: print a
thin is a data

【print】
In [4]: print "sdfds nu1 %d and %f" %(num1,num2)
sdfds nu1 23 and 12.300000



【类型转换】
In [6]: bootx = 1222;

In [7]: bostst =str(bootx)

In [8]: type(bootx)
Out[8]: int

In [9]: type(bostst)
Out[9]: str
In [1]: name ="thinkcore"

In [2]: name.upper()
Out[2]: 'THINKCORE'
【函数定义】

def pritnname(name);
print name;

 

In [3]: def printnamex(name):
...: print name
...: print "echo ok!";
...:

In [4]: print
print printnamex

In [4]: printnamex(1223)
1223
echo ok!

In [5]: box= 12123132;

In [6]: printnamex(box)
12123132
echo ok!

【检查方法是否可调用】
In [7]: callable(printnamex)
Out[7]: True


代码结构

#/usr/bin/env python 开始行
*fdsafdsfdsfdfdsf* 模块文档
import sys 模块导入
debug = True 变量定义
class FooClass (object):
*Foo Class*
pass

def test():
*dsfdsfdsf*
foo = FllClass()
if defbug
print 'ran test();


if _name_ == '__main__' : 定义了 如果是导入就不执行 如果是命令行就执行
test() 主程序

如果被模块导入 __name__ 的值就是模块名字
如果模块是直接执行 __name__的值是 ’__main__'

 


类型转换】

str() repr() format() : 将非字符型数据转换字符
list() 将字符串转为列表
tuple(s) 将字串S 转换为元组
set(s) 将字串S转为集合
dict(d) 创建字典 其D 必须是 (k,vlaue)

数字典型:

python 的数字字面 : 布尔型: 整数 浮点 复数
True False


字符类型 :

字符串字面量 : 单引号 双引号 三引号

定义unicode : 在字符串前面加 u

strl =u"hello word"

文档字串 : 模块 类 或函数的第一条是一个字符的话 叫文档字串
In [12]: def printfunction():
....: "thinkcore is my fennrd"
....: print "zhong guo dianxin"
....:

In [13]: printfunction()
zhong guo dianxin

In [14]: printfunction.__doc__ 【对象名称引用到 字符串 文档字符串 】
Out[14]: 'thinkcore is my fennrd'

In [15]:

适用所有序列的操作和方法
s[i]
s[i:j] s[i:j:len] 切片运算


lens() s 中最小值

In [3]: str1 ="1234567890"
In [4]: min(str1)
Out[4]: '0'

In [5]: max(str1)
Out[5]: '9'


index查找字符串

In [1]: str2="www.thinkcore.com"

In [2]: str2.index("core")
Out[2]: 9

In [3]: str2.index("core",4,9)


replace(old,new[]) 替换字符串


In [1]: str1 ="thinkcore.net.com"

In [2]: str1.replace('net','cn')
Out[2]: 'thinkcore.cn.com'

split 划分对象

In [4]: str1.split('.')
Out[4]: ['thinkcore', 'net', 'com']

del 删除
In [7]: print l1
[1, 2, 'thinkcore', 4, 5]

In [8]: del(l1[3])

append 新增
In [7]: print l1
[1, 2, 'thinkcore', 4, 5]

In [8]: del(l1[3])

insert 插入

In [13]: l1.insert(1,'uoot')

In [14]: print l1
[1, 'uoot', 2, 'thinkcore', 5, 99]

pop 弹出元素

In [15]: l1.pop(2)
Out[15]: 2

In [16]: print l1
[1, 'uoot', 'thinkcore', 5, 99]


合并列表 返回新列表 但是不会修改原来列表
In [1]: l1 =[1,2,3,4,5]

In [2]: l2=[6,7,8,9,10]

In [3]: l1+l2
Out[3]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [4]: l1
Out[4]: [1, 2, 3, 4, 5]

In [5]: l2
Out[5]: [6, 7, 8, 9, 10]

字串连接

In [6]: srt1 ="hello"

In [7]: srt2 ="word"

In [8]: srt1 +srt2
Out[8]: 'helloword'

In [9]: srt1
Out[9]: 'hello'

in:成员关系判断字符

In [10]: l1
Out[10]: [1, 2, 3, 4, 5]

In [11]: 2 in l1
Out[11]: True

 


字典 dict
{}






条件语句

【if】

“==” 测试值
“is” 对象一致

In [13]: if l1==l2:
....: print "yes l1==l2"
....: else :
....: print "no l1!=l2"
....:
yes l1==l2

In [14]: x=2

In [15]: y=4
In [17]: if x==y:
....: print " y ==x "
....: elif x<y :
....: print "x<y"
....: else :
....: print "y > x"


while【循环 while】
In [2]: url = "www.thinkcor.com"

In [3]: while url:
...: print url
...: url =url[1:];
...:
www.thinkcor.co
ww.thinkcor.co
w.thinkcor.co
.thinkcor.co
thinkcor.co
hinkcor.co
inkcor.co
nkcor.co
kcor.co
cor.co
or.co
r.co
.co
co
o

切片

In [18]: while x<y:
....: print x, 【打印不想换行在 print 加,】
....: x+=2
....:
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98
In [29]: url ="wwww.thinkcore.com"

In [30]: while url:
print url
url = url[:-1]
x +=1;
if x >7:
break
....:
wwww.thinkcore.com
wwww.thinkcore.co
wwww.thinkcore.c
wwww.thinkcore.
wwww.thinkcore
wwww.thinkcor
wwww.thinkco
wwww.thinkc



【for】


for experssion1 in iterable:
for suite

else

else suite


In [3]: for x in url:
print x,
...:
w w w . t h i n k c o r e . c o m 序列迭代 :---

 

In [15]: for i in range(1,101):
....: sum +=i;
....:

In [16]: print sum

xrange(1,100) 比 range() 节约内存

指定索引:*********

for i in range(1,len(11),2)
print l1[i]




迭代【重复做一件事】

iterable (可迭代)对象
支持每次返回自己所包含的一个成员对象
对象实现了__iter__ 方法


In [6]: l1.__iter__()
Out[6]: <listiterator at 0x1eea490>

In [7]: l1.__iter__()
Out[7]: <listiterator at 0x1eea250>

In [8]: l1.__iter__()
Out[8]: <listiterator at 0x1eea290>

In [9]: l1.__iter__()
Out[9]: <listiterator at 0x1eea510>
每次获取迭代对象 迭代器
In [1]: l1 =['noe','two','there','fore']

In [2]: il = l1.__iter__()

In [6]: il.next()
Out[6]: 'noe'

In [7]: il.next()
Out[7]: 'two'

In [8]: il.next()
Out[8]: 'there'

In [9]: il.next()
Out[9]: 'fore'

实现元素遍历接口
迭代器不可逆。

In [10]: i2 = iter(l1)

In [11]: i2.next()
Out[11]: 'noe'

In [12]: i2.next()
Out[12]: 'two'

可跌代对象 list str tuple 非序列 dict file

for 循环开始时,会通过迭代协议传递给iter() 内置函数 从而能
够从可迭代对象中获取得到一个迭代器,返回对象含有需要的next 方法。

 

In [1]: l1=[1,2,3,4,5,6]

In [2]: l2=[]

 

In [4]: for i in l1:
...: l2.append(i**2)
...:

In [5]: print l2
[1, 4, 9, 16, 25, 36]

In [6]:

【基于已有列表生成新列表 方式 列表解析】


In [7]: l3 = [i**2 for i in l1 ] 【先写循环体 在写表达式 】

In [8]: print l3
[1, 4, 9, 16, 25, 36]

先写循环体 在写表达式

条件解析
In [10]: l4 = [i**2 for i in l1 if i>=3 ]

In [11]: print l4
[9, 16, 25, 36]

In [17]: for i in [ i**2 for i in range(1,11) ] :print i/2,
0 2 4 8 12 18 24 32 40 50

In [18]:


获取.log 文件结尾方法【s1.endswith('.log')】
In [5]: s1 = 'hello.log'

In [6]: s1.endswith('.log')
Out[6]: True


In [7]: fil3 = [ i for i in files if i.endswith('.log') ]

In [8]: print fil3
['repair.log', 'yum.log', 'ntp.log', 'cloud-init.log', 'boot.log', 'dracut.log', 'agent.log']

In [9]:


二级嵌套

In [9]: l1 = ['x','y','z']

In [10]: l2 = [1,2,3]

In [11]: l3 = [ (i,j) for i in l1 for j in l2 ]

In [12]: print l3
[('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)]

In [13]:


In [13]: l3 =[ (i,j) for i in l1 for j in l2 if j !=1 ]

In [14]: print l3
[('x', 2), ('x', 3), ('y', 2), ('y', 3), ('z', 2), ('z', 3)]


生成器 表达式 节约内存


In [17]: (i**2 for i in range(1,22) )
Out[17]: <generator object <genexpr> at 0x1b295f0>
返回一个迭代器

In [18]: lg = (i**2 for i in range(1,22) )

In [20]: lg.next()
Out[20]: 1

In [21]: lg.next()
Out[21]: 4


系列过长 并且每次只需要获取一个元素时 应当考虑使用生成器而不是列表接解析


【enumerate】
获取 元素的索引 和元素本身

In [1]: url = 'www.thinkcore.com'

In [2]: enumerate(url)
Out[2]: <enumerate at 0xeb4410>

In [3]: g1 = en
%env enumerate

In [3]: g1 = enumerate(url)

In [4]: g1.next()
Out[4]: (0, 'w')

In [5]:

In [5]: g1.next()
Out[5]: (1, 'w')

In [6]: g1.next()
Out[6]: (2, 'w')

In [7]: g1.next()
Out[7]: (3, '.')


文件对象【文件对象】


内置函数 open() 打开文件和创建文件对象

open ( name [,mode [,bufsize]])

参数 :文件名 模式 缓冲区

open 函数返回一个文件对象
mode 指定文件打开模式
bufsize 定义输出缓存 【 0 无缓存 1 使用缓存(1行) 负数表示系统默认缓存大小 】

简单模式:

r: 只读
open('/var/xx.og','r')
w: 写入
a: 附加
在模式使用 “+” 表示同事支持输入 输出操作
如 r+ w+ a+

模式后附加b 表示二进制方式打开
如 rb wb+

In [1]: f1 = open('/home/thinkfile/1.txt','r')

In [2]: f1.next()
Out[2]: 'thinkcore dsf tydsfd\n'

In [3]:

In [3]: f1.next()
Out[3]: 'tyesdf fdsfdsf\n'

In [4]: f1.next()
Out[4]: '33333333333\n'

In [5]: f1.next()
Out[5]: '4\n'

fileno() 返回文件描述符


In [6]: f1.fileno()
Out[6]: 4
关于open 模式:

w 以写方式打开
a 以追加模式打开
r+ 以读写模式打开
w+ 以读写模式打开 (参见 w )
a+ 以读写模式打开 (参见 a )
rb 以二进制读模式打开
wb 以二进制写模式打开 (参见 w )
ab 以二进制追加模式打开 (参见 a )
rb+ 以二进制读写模式打开 (参见 r+ )
wb+ 以二进制读写模式打开 (参见 w+ )
ab+ 以二进制读写模式打开 (参见 a+ )

f.write(“str”) #把str写到文件中,write()方法不会在str后加上一个换行符

f.writelines(seq) #把seq的内容全部写到文件中(多行一次性写入)。这个函数也只是忠实地写入,不会在每行后面加上任何东西。

f.close() #关闭文件。在读命令或者写命令结束时,需要用关闭。如果文件关闭后依然操作,会抛出ValueError: I/O operation on closed file

f.tell() #返回文件操作标记的当前位置,以文件的开头为起点

fp.next() #返回下一行内容,并将文件操作标记位移到下一行。把一个file用于for … in file这样的语句时,就是调用next()函数来实现遍历的。

fp.seek(offset[,whence])#将文件操作标记为移动到offset位置。

每次返回一行
In [17]: f1 = open('/home/thinkfile/1.txt','r')

In [18]: f1.readline()
Out[18]: 'thinkcore dsf tydsfd\n'

In [19]: f1.readline()
Out[19]: 'tyesdf fdsfdsf\n'

In [20]: f1.readline()
Out[20]: '33333333333\n'

In [21]: f1.readline()
Out[21]: '4\n'

返回文件指针在文件的位置
In [26]: f1.tell()
Out[26]: 149

f1.seek (offset [, whence]) 偏移 wence 是开始位置 offset 偏移量

移动指针

whence : 0 从文件头 (默认—不定义)

1 从当前位置
2 :文件尾部

 

In [3]: f1.seek(1,0)

In [4]: f1.tell()
Out[4]: 1

read(10) 读取10个字节


In [11]: f1.name 【访问当前文件名称】
Out[11]: '/home/thinkfile/1.txt'

In [31]: f2.flush() 【把数据从缓冲区写到文件上 】


函数 【函数】


In [1]: def f1():
...: x=3
...: def f2():
...: y="hellow"
...: print x,y
...: return f2
...:

In [2]: f1() 得到函数内存
Out[2]: <function __main__.f2>

In [4]: a1 = f1() 赋值给a1 a1 就是一个函数f2()

In [7]: type(a1)
Out[7]: function

In [8]: print a1
<function f2 at 0x1a61230>

In [9]: a1() 调用函数
3 hellow

函数闭合 : 内层函数调用外层函数 而返回时 内层函数会记住外层函数的变量

Python 闭包:

变量名引用 : 本地 函数 全局 内置


 


def f5(x):
x.pop();
print x


f5(L1[:]); // 传递L1 列表副本 修改后不会造成实际L1参数的变化


def F1(*x):
print x


* 定义函数时使用* 开头的参数 可以用于任意多基于位置的关键字的参数

2-In [6]: def f2(**x):
...: print x
...:

In [7]: f2(y=2,r=4,t=4)
{'y': 2, 'r': 4, 't': 4}

调用函数时使用的可变参数要求“
定义函数使用 * 收集位置参数
定义函数使用 ** 收集关键字参数



混用 :

In [7]: f2(y=2,r=4,t=4)
{'y': 2, 'r': 4, 't': 4}

In [8]: def f1(x, *y):
...: print x ,y
...:

In [9]: f1(1,32,42)
1 (32, 42)

可变参数不能写在左边
In [13]: def f1(*y ,x):
....: print y ,x
....:
File "<ipython-input-13-1be8d594c513>", line 1
def f1(*y ,x):
^
SyntaxError: invalid syntax


分解:

In [1]: l1 = ['tink','sunm','nots']

In [2]: x,y,z =l1

In [3]: print x,y,z
tink sunm nots

In [4]:
函数分解

In [4]: def f1(x,c,v):
...: print x,c,v
...:

In [7]: f1(*l1)
tink sunm nots

【lambda args: expression [] 运算符表达式】


lambda x,y: print x,y

 

posted @ 2017-07-28 16:23  thinkcore  阅读(193)  评论(0编辑  收藏  举报