- 规范
- 内置函数
- 基础
- input("")
- x = int(input(“Please enter an integer:”))
- print(“%s”, % s1)
- %.3s % (“abcdef”)取3字符
- %.* s % (2, “abcd”)取2字符)
- %r repr()显示字符串
- %c 单个字符
- %b 二进制整数
- %x 十六进制整数
- %d 十进制整数
- %i 十进制整数
- %o 八进制整数
- %e %E 指数(基底分别为e E)
- %-10.3f %-10.3F 浮点数
- 10位宽, 小数精确3位, 右对齐
- %g %G 指数(e E)或浮点数(根据显示长度决定)
- %% 字符%
- print(“c is %s, e is %i” % (c, e)
- str(1)
- int(“1”)
- range(1, 10)
- exec(”)
- execfile(r’a.py’)
- eval(‘2 * 3’, globals, locals)
- 执行字符串中的表达式
- ast.literal_eval
- compile(str, filename, kind)
- 编译字符串为模块
- kind取值: single单语句, exec多语句, eval一个表达式
- assert 1 != 1
- repr(list)
- map(str, range(100))
- filter()
- reduce()
- locals()
- isinstance(value, list)
- hasattr(obj, ‘call’)
- type(l)
- chr(48)
- unichr
- ord(‘0’)
- bool()
- iter()
- next()
- zip(‘abc’, ‘123’)
- apply()
- 文件
- spath = “D:/a.txt”
- f = open(spath, “w”)
- f.write(“a\n”)
- f.writelines(“b”)
- f.close()
- f = open(spath, “r”)
- for line in f:
- f.readline()
- f.close()
- 文档
- dir(list)
- help(s.replace)
- 类型
- 基本类型
- 数字
- 1.2, 3+4j, Decimal, Fraction
- 字符串
- 列表
- 字典
- 元组
- 文件
- 集合
- 其他类型
- 编程单元
- 实现相关类型
- 扩展属性
- dict = type(‘dict’, (dict,), {})
- d = dict()
- d.a = 1
- 序列
- [1,
- 2]
- [1, [2]]
- len(l)
- l[0]
- l[-1]
- l[1:3]
- l[1:]
- l[:3]
- l[:-1]
- l[:]
- l + l
- l * 2
- del l[1:3]
- 字符串
- 不可变
- r’a’ R’a’ u’a’ U’a’ b’a’ B’a’
- ‘abc\
- def’
- ‘a’ ‘b’
- ‘a’ “a” '''a''' """a"""
- s.startswith(‘a’)
- s.find(‘a’)
- s.replace(‘a’, ‘A’)
- s.split(’,’)
- s.join(list)
- s.upper()
- s.isalpha()
- s.isdigit()
- s.rstrip()
- ‘%s, %s’ % (‘a’, ‘b’)
- ‘{0},{1}‘.format(‘a’, ‘b’)
- if ‘a’ in name:
- 列表
- l.append(‘h’)
- l.pop(2)
- l.sort()
- l.reverse()
- print(l)
- for x in word:
- [2 * i for i in [2,3,4] if i > 2]
- 列表解析
- [row[1] + 1 for row in M]
- [M[i][i] for i in [0, 1, 2]]
- {ord(x) for x in ‘spaam’}
- {x: ord(x) for x in ‘spaam’}
- 元组
- 不可变
- (‘a’, ‘b’)
- (1,) + (2,)
- t.index(‘c’)
- t.count(‘c’)
- set
- s = set(‘a’)
- set([1])
- s.add(2)
- s1, s2
- s1 & s2
- s1 | s2
- s1 - s2
- {x ** 2 for x in [1,2,3,4]}
- 字典
- d = {‘a’: ‘aaa’, ‘b’: ‘bbb’, ‘c’: 12}
- d[‘d’] = 3
- d.items()
- d.keys()
- len(d)
- del d[‘a’]
- d.get(‘a’, 0)
- d[‘a’]
- for key in d:
- if ‘a’ in d:
- d[‘a’] if ‘a’ in d else 0
- 文件
- f = open(‘data.txt’, ‘w’)
- f.write(‘a’)
- f.close()
- text = f.read()
- 语句
- 语句
- 运算符
-
- & | ^ ~
- 按位与 或 异或 翻转(x 变为 -(x + 1))
- not and or
-
- //
- code if None else 0
- True and 1 or 0
- 条件
- if x < 0:
- elif x == 0:
- else:
- 循环
- for x in a:
- else:
- while running:
- else:
- 函数
- 函数
- def sum(a, b=2, *args, **kwargs):
- *args得到元组, kwargs得到字典
- ''' doc
- string'''
- global x
- nonlocal y
- return a + b
- sum(a=1)
- sum.doc
- def make_repeater(n):
- 生成器
- def gn2():
- def gn(N):
- for i in range(N):
- yield from gn2()
- g = gn()
- next(g)
- g.send(1)
- asyncio模块
- @asyncio.coroutine
- def f():
- yield from asyncio.sleep(1)
- loop = asyncio.get_event_loop()
- tasks = [asyncio.async(f())]
- loop.run_until_complete(asyncio.wait(tasks))
- loop.close()
- 协程
- @types.coroutine
- def f2():
- async def f():
- try:
- except StopIteration:
- 协程asyncio
- async f():
- loop = asyncio.get_event_loop()
- tasks = [asyncio.ensure_future(f())]
- loop.run_until_complete(asyncio.wait(tasks))
- loop.close()
- 协程属性
- 属性
- oop
- class Base:
- metaclass = models.SubfieldBase
- description = ”
- def init(self, name):
- self就是this
- del(self)
- str(self)
- lt(self)
- getitem(self, key)
- x[key]索引时调用
- len(self)
- super(Base, self).init(*args, **kwargs)
- self.data = []
- def add(self, x)
- @classmethod
- def t1(cls):
- @staticmethod
- def t2():
- class Child(Base):
- oChild = Child()
- oChild.add(“str1”)
- oChild.data
- oChild.plus(2, 3)
- 模块
- .pyc是字节编译文件
- name 等于’main’时程序本身使用运行, 否则是引用
- a.py
- b.py
- from a import add_func
- import add_func as f
- from a import *
- init.py
- 包路径
- 环境变量PYTHONPATH中的值
- import sys
- import os
- sys.path
- sys.path.append(os.getcwd() + “\parent\child”)
- 异常
- if s == "":
- raise Exception(“must not be empty.”)
- try:
- except Exception as err:
- except Exception, err
- print(‘Error %d: %s’ % (e.args[0], e.args[1]))
- except:
- finally:
- else: