python学习
基础语法
标识符
- 首字母必须是字母或者下划线
_ - 其他部分由字母、数字、下划线组成
- 大小写敏感
- python3 可中文也可非ASCII标识符
python保留字
import keyword
print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
注释
python中'和"一样
#单行注释
'''
多行注释
'''
"""
多行注释
"""
缩进
python不使用大括号,使用缩进对齐
if expression :
XXX
else :
XXX
多行连接
var = 1 + \
2 + \
3
print(var)
#6
数字类型
python中数字有四种类型:整数、布尔型、浮点数和复数
字符串
- python中单引号、双引号使用完全相同
- 转义字符
\ r'test\ntest',r可以使\n不转义"this " "is " "string"输出this is string+运算符连接字符,*运算符重复字符- 检索从左到右从0开始,从右到左从-1开始
- 一个字符就是一个长度为1的字符串
var = "this " "is " "string"
print(var)
# this is string
print(var * 2)
# this is stringthis is string
print(var + '111')
# this is string111
print('ssss\nsssss')
# ssss
# sssss
print(r"ssss\nssss")
# ssss\nssss
print(var[0:])
# this is string
print(var[0::1])
# this is string
print(var[0:-1:1])
# this is strin
print(var[0:-1:2])
# ti ssrn
'''
this is string
this is stringthis is string
this is string111
ssss
sssss
ssss\nssss
this is string
this is string
this is strin
ti ssrn
'''
一行多条语句
import sys; x = 'test'; sys.stdout.write(x + '\n')
'''
test
'''
多个语句组成代码组
首行以关键字开始,以冒号( : )结束,该行之后的一行或多行代码构成代码组
if expression :
suite
elif expression :
suite
else :
suite
输出
var = 'test'
# 换行输出
print(var)
print('1')
print('---------')
# 不换行输出
print(var, end=" ") # 以空格分隔
print('1', end=" ")
print()
'''
test
1
---------
test 1
'''
导入模块
在 python 用 import 或者 from…import 来导入相应的模块
import sys
from sys import argv,path
数据类型
python的变量就是对象
python变量直接赋值,不需要声明
a = 1
b = 1.2
c = 'test'
多个变量赋值
a = b =c =1
a, b, c =1, 2, 'test'
不可变数据
Number(数字)
支持int、float、bool、complex(复数)
a, b, c, d = 20, 5.5, True, 4+3j
print(type(a), type(b), type(c), type(d))
'''
<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>
'''
type()函数查询变量的类型
a = 111
isinstance(a, int)
'''
True
'''
isinstance(x,x)对比对象类型
type()不会认为子类是一种父类类型isinstance()会认为子类是一种父类类型
class A:
pass
class B(A):
pass
print(isinstance(A(), A))
# True
print(type(A()) == A)
# Ture
print(isinstance(B(), A))
# Ture
print(type(B()) == A)
# False
'''
True
True
True
False
'''
bool值处理
print(issubclass(bool, int))
# Ture
print(True==1)
# Ture
print(False==0)
# Ture
print(True+1)
# 2
print(False+1)
# 1
var1 = 1
print(var1 is True)
# False
var2 = 0
print(var2 is False)
# False
'''
True
True
True
2
1
False
False
'''
删除对象
del a
del var1,var2
'''
再次print会报错
'''
数值运算
- 除法
/返回一个浮点数,//返回一个整数 *乘法,**乘方%取余- 混合运算时整型转换为浮点型
- 复数使用
complex(a,b)表示a+bj
String(字符串)
字符串截取格式
变量名[头下标:尾下标]
从前面索引 0 1 2 3 4 ……
从后面索引 -1 -2 -3 -4 -5 ……
从前面截取 :1 2 3 4:
从后面截取 :-4 -3 -2 -1:
str = 'test'
print(str)
# test
print(str[0])
# t
print(str[0:]) # 输出所有字符
# test
print(str[0:-1]) # 输出第一个到倒数第二个
# tes
print(str[2:4]# 输出第三个到第四个
# st
print(str * 2)
# testtest
print(str + 're')
# testre
print(str[0], str[3])
# t t
'''
test
t
test
tes
st
testtest
testre
t t
'''
python字符串不能改变,诸如str[n]='?'的赋值会报错
Tuple(元组)
- 元组元素不能更改
- 元组写在小括号内,以
,分隔 - 各元素类型可以不同
- 元组的索引切片操作与string一样
tuple = (1, 1.2, 'test', 'dou')
tuple2 = (1, 'test2')
tuple3 = (1,) # 单个元素后面加逗号
tuple4 = () # 空元组
print(tuple4)
# ()
print(tuple)
# (1, 1.2, 'test', 'dou')
print(tuple3)
# (1,)
print(tuple[0]) # 输出第一个元素
# 1
print(tuple[1:3]) # 输出第二个到第三个元素
# (1.2, 'test')
print(tuple[0:]) # 输出所有元素
# (1, 1.2, 'test', 'dou')
print(tuple[:]) # 输出所有元素
# (1, 1.2, 'test', 'dou')
print(tuple[:3]) # 输出第三个及前面的所有
# (1, 1.2, 'test')
print(tuple * 2)
# (1, 1.2, 'test', 'dou', 1, 1.2, 'test', 'dou')
print(tuple + tuple2)
# (1, 1.2, 'test', 'dou', 1, 'test2')
'''
()
(1, 1.2, 'test', 'dou')
(1,)
1
(1.2, 'test')
(1, 1.2, 'test', 'dou')
(1, 1.2, 'test', 'dou')
(1, 1.2, 'test')
(1, 1.2, 'test', 'dou', 1, 1.2, 'test', 'dou')
(1, 1.2, 'test', 'dou', 1, 'test2')
'''
可变数据
List(列表)
- 索引截取方式与元组相同
- 截取后成为一个新列表
- 元素在打方括号中,以逗号分隔
- 列表的元素可改变
- 元素可以是元组
list = ['test', 1, 1.2, 999]
list2 = [1, 'test']
print(list) # 输出完整列表
# ['test', 1, 1.2, 999]
print(list[0]) # 输出列表第一个元素
# test
print(list[1:3]) # 从第二个开始输出到第三个元素
# [1, 1.2]
print(list[2:]) # 输出从第三个元素开始的所有元素
# [1.2, 999]
print(list2 * 2) # 输出两次列表
# [1, 'test', 1, 'test']
print(list + list2) # 连接列表
# ['test', 1, 1.2, 999, 1, 'test']
list3 = [1, 2, 3, 4, 5]
print(list3)
# [1, 2, 3, 4, 5]
list3[0] = 'test' # 修改第一元素
print(list3)
# ['test', 2, 3, 4, 5]
list3[2:4] = [22, 33] # 修改第三个到第四元素
print(list3)
# ['test', 2, 22, 33, 5]
list4 = [1, 2, 3, 4, 5]
print(list4)
# [1, 2, 3, 4, 5]
print(list4[-1::-1])
[5, 4, 3, 2, 1]
# 第一个-1表示从最后一个开始
# 中间为空表示移动到列表末,最后一个-1为步长,-表示逆向
print(list4[-2:0:-1])
# [4, 3, 2]
print(list4[-1::])
# [5]
'''
['test', 1, 1.2, 999]
test
[1, 1.2]
[1.2, 999]
[1, 'test', 1, 'test']
['test', 1, 1.2, 999, 1, 'test']
[1, 2, 3, 4, 5]
['test', 2, 3, 4, 5]
['test', 2, 22, 33, 5]
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
[4, 3, 2]
[5]
'''
Set(集合)
创建格式
parame = {value1, value2, ……}
or
set(value)
set() # 创建一个空集合
sites = {1, 'test', '123'}
print(sites) # 输出集合,重复的元素被自动去掉
# {1, '123', 'test'}
# 成员测试
if 'test' in sites:
print('test 在集合中')
else:
print('test 不在集合中')
# set可以进行集合运算
a = set('abracadabra')
b = set('alacazam')
print(a)
print(a - b) # a 和 b 的差集
print(a | b) # a 和 b 的并集
print(a & b) # a 和 b 的交集
print(a ^ b) # a 和 b 中不同时存在的元素
'''
{1, '123', 'test'}
test 在集合中
{'a', 'b', 'r', 'c', 'd'}
{'b', 'd', 'r'}
{'a', 'm', 'r', 'b', 'c', 'd', 'l', 'z'}
{'c', 'a'}
{'d', 'l', 'r', 'm', 'z', 'b'}
'''
Dictionary(字典)
- 字典是无序的,依靠键值对来存取
- 字典用
{}标识,键(key) : 值(value) key不可变,并且是唯一的- 使用
{}创建空字典
创建字典
dict = {} # 空字典
dict[2] = 'test'
dict['test'] = 1
print(dict)
# {2: 'test', 'test': 1}
dict2 = {'test': 1, 1: 'dddd'}
print(dict2)
# {'test': 1, 1: 'dddd'}
print(dict[2], dict['test']) # 输出2,test的值
# test 1
print(dict2.keys()) # 输出所有键名
# dict_keys(['test', 1])
print(dict2.values()) # 输出所有键值
# dict_values([1, 'dddd'])
'''
{2: 'test', 'test': 1}
{'test': 1, 1: 'dddd'}
test 1
dict_keys(['test', 1])
dict_values([1, 'dddd'])
'''
数据类型转换
class int(x, base=10)
# x为数值型时,不写base,直接取整,x为str时,base为转换前的进制
print(int(3.6))
print(int(-11.2))
print(int('12', 16))
'''
3
-11
18
'''
class float([x])
# 将整数和字符串转换成浮点数
print(float(1))
print(float(-11.2))
print(float('12'))
'''
1.0
-11.2
12.0
'''
class complex([real[, imag]])
# 创建一个复数
print(complex(1))
print(complex(1+2j))
print(complex('1+3j'))
print(complex(1, 2))
'''
(1+0j)
(1+2j)
(1+3j)
(1+2j)
'''
class str(object='')
# 将对象转化为适于人阅读的形式
s = 'test'
print(str(s))
# test
repr(object)
# 将对象转化为供解释器读取的形式
dad = 'test'
print(repr(dad))
'''
'test'
'''
eval(expression[, globals[, locals]])
# 用来执行一个字符串表达式,并返回表达式的值
print(eval('pow(2,2)'))
print(eval('2 * 2'))
'''
4
4
'''
tuple( iterable )
# 将可迭代系列(如列表)转换为元组
# tuple() 可以将字符串,列表,字典,集合转化为元组
list1= ['12', '34', '56', '78']
print(tuple(list1))
# ('12', '34', '56', '78')
list( seq )
# 用于将元组或字符串转换为列表
aTuple = (123, 'Google', 'Runoob', 'Taobao')
list1 = list(aTuple)
print ("列表元素 : ", list1)
# [123, 'Google', 'Runoob', 'Taobao']
str = "Hello World"
list2=list(str)
print ("列表元素 : ", list2)
# 列表元素 : ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
class set([iterable])
# set() 函数创建一个无序不重复元素集
set('test')
class dict(**kwarg)
'''
class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
创建一个字典
'''
dict(a='a', b='b', t='t') # 传入关键字
dict(zip(['one', 'two', 'three'], [1, 2, 3])) # 映射函数方式来构造字典
dict([('one', 1), ('two', 2), ('three', 3)]) # 可迭代对象方式来构造字典
class frozenset([iterable])
# 返回一个冻结的集合,冻结后集合不能再添加或删除任何元素
print(frozenset('test'))
chr(i)
# 返回值是当前整数对应的 ASCII 字符
print(chr(0x30))
print(chr(48))
#0
#0
ord(c)
# 返回对应的 ASCII 数值,或者 Unicode 数值
print(ord('a'))
#97
hex(x)
# 将10进制整数转换成16进制,以字符串形式表示
print(hex(20))
#0x14
oct(x)
# 将一个整数转换成 8 进制字符串
print(oct(10))
#0o12
注释
# 单行注释
'''
多行注释
'''
"""
多行注释
"""
运算符
算数运算符
a = 4
b = 3
c = 0
c = a + b
print("c 的值为:", c)
# 7
c = a - b
print("c 的值为:", c)
# 1
c = a * b
print("c 的值为:", c)
# 12
c = a / b
print("c 的值为:", c)
# 1.3333333333333333
c = a % b
print("c 的值为:", c)
# 1
a = 4
b = 3
c = a ** b # 乘方
print("c 的值为:", c)
# 64
a = 10
b = 5
c = a // b # 取整除
print("c 的值为:", c)
# 2
'''
c 的值为: 7
c 的值为: 1
c 的值为: 12
c 的值为: 1.3333333333333333
c 的值为: 1
c 的值为: 64
c 的值为: 2
'''
比较运算符
a = 21
b = 10
c = 0
if (a == b):
print("a 等于 b")
else:
print("a 不等于 b")
# a 不等于 b
if (a != b):
print("a 不等于 b")
else:
print("a 等于 b")
# a 不等于 b
if (a < b):
print("a 小于 b")
else:
print("a 大于等于 b")
# a 大于等于 b
if (a > b):
print("a 大于 b")
else:
print("a 小于等于 b")
# a 大于 b
# 修改变量 a 和 b 的值
a = 5
b = 20
if (a <= b):
print("a 小于等于 b")
else:
print("a 大于 b")
# a 小于等于 b
if (b >= a):
print("b 大于等于 a")
else:
print("b 小于 a")
# b 大于等于 a
'''
a 不等于 b
a 不等于 b
a 大于等于 b
a 大于 b
a 小于等于 b
b 大于等于 a
'''
赋值运算符
a = 21
b = 10
c = 0
c = a + b
print("c 的值为:", c)
# 31
c += a
print("c 的值为:", c)
# 52
c *= a
print("c 的值为:", c)
# 1092
c /= a
print("c 的值为:", c)
# 52.0
c = 2
c %= a
print("c 的值为:", c)
# 2
c **= a
print("c 的值为:", c)
# 2097152
c //= a
print("c 的值为:", c)
# 99864
'''
c 的值为: 31
c 的值为: 52
c 的值为: 1092
c 的值为: 52.0
c 的值为: 2
c 的值为: 2097152
c 的值为: 99864
'''
位运算符
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c = 0
c = a & b # 12 = 0000 1100
print("c 的值为:", c)
# 12
c = a | b # 61 = 0011 1101
print("c 的值为:", c)
# 61
c = a ^ b # 49 = 0011 0001
print("c 的值为:", c)
# 49
c = ~a # -61 = 1100 0011
print("c 的值为:", c)
# -61
c = a << 2 # 240 = 1111 0000
print("c 的值为:", c)
# 240
c = a >> 2 # 15 = 0000 1111
print("c 的值为:", c)
# 15
'''
c 的值为: 12
c 的值为: 61
c 的值为: 49
c 的值为: -61
c 的值为: 240
c 的值为: 15
'''
逻辑运算符
a = 10
b = 20
if (a and b):
print("变量 a 和 b 都为 true")
else:
print("变量 a 和 b 有一个不为 true")
# 变量 a 和 b 都为 true
if (a or b):
print("变量 a 和 b 都为 true,或其中一个变量为 true")
else:
print("变量 a 和 b 都不为 true")
# 变量 a 和 b 都为 true,或其中一个变量为 true
# 修改变量 a 的值
a = 0
if (a and b):
print("变量 a 和 b 都为 true")
else:
print("变量 a 和 b 有一个不为 true")
# 变量 a 和 b 有一个不为 true
if (a or b):
print("变量 a 和 b 都为 true,或其中一个变量为 true")
else:
print("变量 a 和 b 都不为 true")
# 变量 a 和 b 都为 true,或其中一个变量为 true
if not (a and b):
print("变量 a 和 b 都为 false,或其中一个变量为 false")
else:
print("变量 a 和 b 都为 true")
# 变量 a 和 b 都为 false,或其中一个变量为 false
'''
变量 a 和 b 都为 true
变量 a 和 b 都为 true,或其中一个变量为 true
变量 a 和 b 有一个不为 true
变量 a 和 b 都为 true,或其中一个变量为 true
变量 a 和 b 都为 false,或其中一个变量为 false
'''
成员运算符
a = 10
b = 20
list = [1, 2, 3, 4, 5]
if (a in list):
print("变量 a 在给定的列表中 list 中")
else:
print("变量 a 不在给定的列表中 list 中")
# 变量 a 不在给定的列表中 list 中
if (b not in list):
print("变量 b 不在给定的列表中 list 中")
else:
print("变量 b 在给定的列表中 list 中")
# 变量 b 不在给定的列表中 list 中
# 修改变量 a 的值
a = 2
if (a in list):
print("变量 a 在给定的列表中 list 中")
else:
print("变量 a 不在给定的列表中 list 中")
# 变量 a 在给定的列表中 list 中
'''
变量 a 不在给定的列表中 list 中
变量 b 不在给定的列表中 list 中
变量 a 在给定的列表中 list 中
'''
身份运算符
a = 20
b = 20
if (a is b):
print("a 和 b 有相同的标识")
else:
print("a 和 b 没有相同的标识")
# a 和 b 有相同的标识
if (id(a) == id(b)):
print("a 和 b 有相同的标识")
else:
print("a 和 b 没有相同的标识")
# a 和 b 有相同的标识
# 修改变量 b 的值
b = 30
if (a is b):
print("a 和 b 有相同的标识")
else:
print("a 和 b 没有相同的标识")
# a 和 b 没有相同的标识
if (a is not b):
print("a 和 b 没有相同的标识")
else:
print("a 和 b 有相同的标识")
# a 和 b 没有相同的标识
'''
a 和 b 有相同的标识
a 和 b 有相同的标识
a 和 b 没有相同的标识
a 和 b 没有相同的标识
'''
优先级
| 运算符 | 描述 |
|---|---|
| ** | 指数 (最高优先级) |
| ~ + - | 按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@) |
| * / % // | 乘,除,求余数和取整除 |
| + - | 加法减法 |
| >> << | 右移,左移运算符 |
| & | 位 ‘AND’ |
| ^ | | 位运算符 |
| <= < > >= | 比较运算符 |
| == != | 等于运算符 |
| = %= /= //= -= += *= **= | 赋值运算符 |
| is is not | 身份运算符 |
| in not in | 成员运算符 |
| not and or | 逻辑运算符 |
数字(Number)
直接创建,不用特别定义类型
支持int、float、bool、complex(复数)
var = 1
var1 = 'test'
print(var, var1)
# 1 test
del var, var1 # 删除对象
# 8或者16进制表示数字
var = 0x99
var1 = 0o43
print(var, var1)
# 153 35
运算
print(2 + 2)
print(3 - 1)
print(2 * 3)
print(6.3 / 3) # 与浮点数运算结果为浮点数
print(3 ** 2) # 乘方
print(6.5 // 3) # 向下取整
var = 'test' # 赋值
print(7 % 3) # 取余
3 * 3
print(_) # 变量_是上一个表达式的值
'''
4
2
6
2.1
9
2.0
1
'''
数据类型转换函数
class int(x, base=10)
# x为数值型时,不写base,直接取整,x为str时,base为转换前的进制
print(int(3.6))
print(int(-11.2))
print(int('12', 16))
'''
3
-11
18
'''
class float([x])
# 将整数和字符串转换成浮点数
print(float(1))
print(float(-11.2))
print(float('12'))
'''
1.0
-11.2
12.0
'''
class complex([real[, imag]])
# 创建一个复数
print(complex(1))
print(complex(1+2j))
print(complex('1+3j'))
print(complex(1, 2))
'''
(1+0j)
(1+2j)
(1+3j)
(1+2j)
'''
数学函数
| abs(x) | 返回数字的绝对值,如abs(-10) 返回 10 |
|---|---|
| ceil(x) | 返回数字的上入整数,如math.ceil(4.1) 返回 5 |
| cmp(x, y) | 如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。 Python 3 已废弃,使用 (x>y)-(x<y) 替换。 |
| exp(x) | 返回e的x次幂(ex),如math.exp(1) 返回2.718281828459045 |
| fabs(x) | 返回数字的绝对值,如math.fabs(-10) 返回10.0 |
| floor(x) | 返回数字的下舍整数,如math.floor(4.9)返回 4 |
| log(x) | 如math.log(math.e)返回1.0,math.log(100,10)返回2.0 |
| log10(x) | 返回以10为基数的x的对数,如math.log10(100)返回 2.0 |
| max(x1, x2,…) | 返回给定参数的最大值,参数可以为序列。 |
| min(x1, x2,…) | 返回给定参数的最小值,参数可以为序列。 |
| modf(x) | 返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示。 |
| pow(x, y) | x**y 运算后的值。 |
| [round(x ,n]) | 返回浮点数 x 的四舍五入值,如给出 n 值,则代表舍入到小数点后的位数。其实准确的说是保留值将保留到离上一位更近的一端。 |
| sqrt(x) | 返回数字x的平方根。 |
随机数函数
| 函数 | 描述 |
|---|---|
| choice(seq) | 从序列的元素中随机挑选一个元素,比如random.choice(range(10)),从0到9中随机挑选一个整数。 |
| [randrange (start,] stop [,step]) | 从指定范围内,按指定基数递增的集合中获取一个随机数,基数默认值为 1 |
| random() | 随机生成下一个实数,它在[0,1)范围内。 |
| [seed(x]) | 改变随机数生成器的种子seed。如果你不了解其原理,你不必特别去设定seed,Python会帮你选择seed。 |
| shuffle(lst) | 将序列的所有元素随机排序 |
| uniform(x, y) | 随机生成下一个实数,它在[x,y]范围内。 |
三角函数
Python包括以下三角函数:
| 函数 | 描述 |
|---|---|
| acos(x) | 返回x的反余弦弧度值。 |
| asin(x) | 返回x的反正弦弧度值。 |
| atan(x) | 返回x的反正切弧度值。 |
| atan2(y, x) | 返回给定的 X 及 Y 坐标值的反正切值。 |
| cos(x) | 返回x的弧度的余弦值。 |
| hypot(x, y) | 返回欧几里德范数 sqrt(xx + yy)。 |
| sin(x) | 返回的x弧度的正弦值。 |
| tan(x) | 返回x弧度的正切值。 |
| degrees(x) | 将弧度转换为角度,如degrees(math.pi/2) , 返回90.0 |
| radians(x) | 将角度转换为弧度 |
数学常量
| 常量 | 描述 |
|---|---|
| pi | 数学常量 pi(圆周率,一般以π来表示) |
| e | 数学常量 e,e即自然常数(自然常数)。 |
函数示例
import math # 导入 math 模块
print("abs(-40) : ", abs(-40)) # 内置
# abs(-40) : 40
print("math.ceil(-45.17) : ", math.ceil(-45.17))
# math.ceil(-45.17) : -45
print((3 > 2) - (3 < 2))
# 1
print("math.exp(-45.17) : ", math.exp(-45.17))
# math.exp(-45.17) : 2.4150062132629406e-20
print("math.fabs(-45.17) : ", math.fabs(-45.17))
# math.fabs(-45.17) : 45.17
print("math.floor(-45.17) : ", math.floor(-45.17))
# math.floor(-45.17) : -46
print("math.log(100.12) : ", math.log(100.12))
# math.log(100.12) : 4.6063694665635735
print("math.log10(100.12) : ", math.log10(100.12))
# math.log10(100.12) : 2.0005208409361854
print("max(80, 100, 1000) : ", max(80, 100, 1000))
# max(80, 100, 1000) : 1000
print("min(80, 100, 1000) : ", min(80, 100, 1000))
# min(80, 100, 1000) : 80
print("math.modf(100.12) : ", math.modf(100.12))
# math.modf(100.12) : (0.12000000000000455, 100.0)
print("math.pow(100, 2) : ", math.pow(100, 2))
# math.pow(100, 2) : 10000.0
# 使用内置,查看输出结果区别
print("pow(100, 2) : ", pow(100, 2))
# pow(100, 2) : 10000
print("round(-100.000056, 3) : ", round(-100.000056, 3))
# round(-100.000056, 3) : -100.0
print("math.sqrt(100) : ", math.sqrt(100))
# math.sqrt(100) : 10.0
import random
print("从 range(100) 返回一个随机数 : ", random.choice(range(100)))
# 从 range(100) 返回一个随机数 : 67
print("从列表中 [1, 2, 3, 5, 9]) 返回一个随机元素 : ", random.choice([1, 2, 3, 5, 9]))
# 从列表中 [1, 2, 3, 5, 9]) 返回一个随机元素 : 5
print("从字符串中 'Runoob' 返回一个随机字符 : ", random.choice('Runoob'))
# 从 1-100 中选取一个奇数
#从字符串中 'Runoob' 返回一个随机字符 : n
print("randrange(1,100, 2) : ", random.randrange(1, 100, 2))
# randrange(1,100, 2) : 45
# 从 0-99 选取一个随机数
print("randrange(100) : ", random.randrange(100))
# randrange(100) : 11
# 第一个随机数
print("random() : ", random.random())
# random() : 0.7601111373084349
# 第二个随机数
print("random() : ", random.random())
# random() : 0.9598748666088929
list1 = [20, 16, 10, 5]
random.shuffle(list1)
print("随机排序列表 : ", list1)
# 随机排序列表 : [10, 5, 20, 16]
random.shuffle(list1)
print("随机排序列表 : ", list1)
随机排序列表 : [16, 20, 5, 10]
print("uniform(5, 10) 的随机浮点数 : ", random.uniform(5, 10))
# uniform(5, 10) 的随机浮点数 : 9.959955410049714
print("uniform(7, 14) 的随机浮点数 : ", random.uniform(7, 14))
# uniform(7, 14) 的随机浮点数 : 11.843622946237328
print("acos(1) : ", math.acos(1))
# acos(1) : 0.0
print("asin(1) : ", math.asin(1))
# asin(1) : 1.5707963267948966
print("atan(1) : ", math.atan(1))
# atan(1) : 0.7853981633974483
print("atan2(10,20) : ", math.atan2(10, 20))
# atan2(10,20) : 0.4636476090008061
print("cos(2*math.pi) : ", math.cos(2 * math.pi))
# cos(2*math.pi) : 1.0
print("hypot(0, 2) : ", math.hypot(0, 2))
# hypot(0, 2) : 2.0
print("sin(math.pi/2) : ", math.sin(math.pi / 2))
# sin(math.pi/2) : 1.0
print("tan(math.pi/4) : ", math.tan(math.pi / 4))
# tan(math.pi/4) : 0.9999999999999999
print("degrees(math.pi/4) : ", math.degrees(math.pi / 4))
# degrees(math.pi/4) : 45.0
print(math.radians(180 / math.pi))
# 1.0
print(math.pi)
# 3.141592653589793
print(math.e)
# 2.718281828459045
'''
abs(-40) : 40
math.ceil(-45.17) : -45
1
math.exp(-45.17) : 2.4150062132629406e-20
math.fabs(-45.17) : 45.17
math.floor(-45.17) : -46
math.log(100.12) : 4.6063694665635735
math.log10(100.12) : 2.0005208409361854
max(80, 100, 1000) : 1000
min(80, 100, 1000) : 80
math.modf(100.12) : (0.12000000000000455, 100.0)
math.pow(100, 2) : 10000.0
pow(100, 2) : 10000
round(-100.000056, 3) : -100.0
math.sqrt(100) : 10.0
从 range(100) 返回一个随机数 : 22
从列表中 [1, 2, 3, 5, 9]) 返回一个随机元素 : 2
从字符串中 'Runoob' 返回一个随机字符 : R
randrange(1,100, 2) : 83
randrange(100) : 92
random() : 0.2392758950765237
random() : 0.7016096413249141
随机排序列表 : [16, 5, 20, 10]
随机排序列表 : [20, 16, 10, 5]
uniform(5, 10) 的随机浮点数 : 9.96850739092334
uniform(7, 14) 的随机浮点数 : 9.03188249118426
acos(1) : 0.0
asin(1) : 1.5707963267948966
atan(1) : 0.7853981633974483
atan2(10,20) : 0.4636476090008061
cos(2*math.pi) : 1.0
hypot(0, 2) : 2.0
sin(math.pi/2) : 1.0
tan(math.pi/4) : 0.9999999999999999
degrees(math.pi/4) : 45.0
1.0
3.141592653589793
2.718281828459045
'''
字符串(String)
字符串截取格式
变量名[头下标:尾下标]
从前面索引 0 1 2 3 4 ……
从后面索引 -1 -2 -3 -4 -5 ……
从前面截取 :1 2 3 4:
从后面截取 :-4 -3 -2 -1:
# 创建字符串
str = 'test'
print(str)
# test
print(str[0])
# t
print(str[0:]) # 输出所有字符
# test
print(str[0:-1]) # 输出第一个到倒数第二个
# tes
print(str[2:4]) # 输出第三个到第四个
# st
print(str * 2)
# testtest
print(str + 're')
# testre
print(str[0], str[3])
# t t
print(str[:-2] + ' ' + 'restart')
# te restart
# 截取再拼接
'''
test
t
test
tes
st
testtest
testre
t t
te restart
'''
python字符串不能改变,诸如str[n]='?'的赋值会报错
转义字符
# 转义字符
print('test' \
+ 'test') # \续行
# testtest
print('\\') # 反斜杠
# \
print('\'') # 单引号
# '
print('\"') # 双引号
# "
# print('\a') # 响铃
print('test \btest') # 退格
# testtest
print('\000') # 空
#
print('1\n1') # 换行
# 1
# 1
print('test\vtest') # 纵向制表符
#testtest
print('test\ttest') # 横向制表符
# test test
print('test eee\r11 33') # \r后面替换前面
# 11 33
print('test\ftest') # 换页
print('\666') # 8进制
# z
print('\x33') # 16进制
# 3
'''
testtest
\
'
"
testtest
1
1
testtest
test test
11 33
testtest
ƶ
3
'''
运算符
# 运算符
print('2' + 'rr') # 连接符
print('test' * 2) # 重复符
print(str[1:2]) # 索引符
# in not in 成员运算符
a = 'hahah'
if 'a' in a:
print('in')
else :
print("not in")
# %格式控制符
'''
2rr
testtest
e
in
'''
字符格式化
print ("我叫 %s 今年 %d 岁!" % ('小明', 10))
#我叫 小明 今年 10 岁!
| 符 号 | 描述 |
|---|---|
| %c | 格式化字符及其ASCII码 |
| %s | 格式化字符串 |
| %d | 格式化整数 |
| %u | 格式化无符号整型 |
| %o | 格式化无符号八进制数 |
| %x | 格式化无符号十六进制数 |
| %X | 格式化无符号十六进制数(大写) |
| %f | 格式化浮点数字,可指定小数点后的精度 |
| %e | 用科学计数法格式化浮点数 |
| %E | 作用同%e,用科学计数法格式化浮点数 |
| %g | %f和%e的简写 |
| %G | %f 和 %E 的简写 |
| %p | 用十六进制数格式化变量的地址 |
| 符号 | 功能 |
|---|---|
| * | 定义宽度或者小数点精度 |
| - | 用做左对齐 |
| + | 在正数前面显示加号( + ) |
| 在正数前面显示空格 | |
| # | 在八进制数前面显示零(‘0’),在十六进制前面显示’0x’或者’0X’(取决于用的是’x’还是’X’) |
| 0 | 显示的数字前面填充’0’而不是默认的空格 |
| % | ‘%%’输出一个单一的’%’ |
| (var) | 映射变量(字典参数) |
| m.n. | m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话) |
三引号
# 三引号
para_str = """这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( \t )。
也可以使用换行符 [ \n ]。
"""
print (para_str)
# 跨多行
'''
这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( )。
也可以使用换行符 [
]。
'''
f-string
# f-string
str = 'test'
f'Hello {str}' # 替换变量
print(f'{1+2}') # 使用表达式
w = {'str': 'test', 'var': 'var'}
print(f'{w["str"]}: {w["var"]}')
'''
3
test: var
'''
函数
| 序号 | 方法及描述 |
|---|---|
| 1 | capitalize() 将字符串的第一个字符转换为大写 |
| 2 | center(width, fillchar) 返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。 |
| 3 | count(str, beg= 0,end=len(string)) 返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数 |
| 4 | bytes.decode(encoding=”utf-8”, errors=”strict”) Python3 中没有 decode 方法,但我们可以使用 bytes 对象的 decode() 方法来解码给定的 bytes 对象,这个 bytes 对象可以由 str.encode() 来编码返回。 |
| 5 | encode(encoding=’UTF-8’,errors=’strict’) 以 encoding 指定的编码格式编码字符串,如果出错默认报一个ValueError 的异常,除非 errors 指定的是’ignore’或者’replace’ |
| 6 | endswith(suffix, beg=0, end=len(string)) 检查字符串是否以 obj 结束,如果beg 或者 end 指定则检查指定的范围内是否以 obj 结束,如果是,返回 True,否则返回 False. |
| 7 | expandtabs(tabsize=8) 把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8 。 |
| 8 | find(str, beg=0, end=len(string)) 检测 str 是否包含在字符串中,如果指定范围 beg 和 end ,则检查是否包含在指定范围内,如果包含返回开始的索引值,否则返回-1 |
| 9 | index(str, beg=0, end=len(string)) 跟find()方法一样,只不过如果str不在字符串中会报一个异常。 |
| 10 | isalnum() 如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False |
| 11 | isalpha() 如果字符串至少有一个字符并且所有字符都是字母或中文字则返回 True, 否则返回 False |
| 12 | isdigit() 如果字符串只包含数字则返回 True 否则返回 False.. |
| 13 | islower() 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False |
| 14 | isnumeric() 如果字符串中只包含数字字符,则返回 True,否则返回 False |
| 15 | isspace() 如果字符串中只包含空白,则返回 True,否则返回 False. |
| 16 | istitle() 如果字符串是标题化的(见 title())则返回 True,否则返回 False |
| 17 | isupper() 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False |
| 18 | join(seq) 以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串 |
| 19 | len(string) 返回字符串长度 |
| 20 | [ljust(width, fillchar]) 返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格。 |
| 21 | lower() 转换字符串中所有大写字符为小写. |
| 22 | lstrip() 截掉字符串左边的空格或指定字符。 |
| 23 | maketrans() 创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。 |
| 24 | max(str) 返回字符串 str 中最大的字母。 |
| 25 | min(str) 返回字符串 str 中最小的字母。 |
| 26 | [replace(old, new , max]) 把 将字符串中的 old 替换成 new,如果 max 指定,则替换不超过 max 次。 |
| 27 | rfind(str, beg=0,end=len(string)) 类似于 find()函数,不过是从右边开始查找. |
| 28 | rindex( str, beg=0, end=len(string)) 类似于 index(),不过是从右边开始. |
| 29 | [rjust(width,, fillchar]) 返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度 width 的新字符串 |
| 30 | rstrip() 删除字符串末尾的空格或指定字符。 |
| 31 | split(str=””, num=string.count(str)) 以 str 为分隔符截取字符串,如果 num 有指定值,则仅截取 num+1 个子字符串 |
| 32 | [splitlines(keepends]) 按照行(‘\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。 |
| 33 | startswith(substr, beg=0,end=len(string)) 检查字符串是否是以指定子字符串 substr 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查。 |
| 34 | [strip(chars]) 在字符串上执行 lstrip()和 rstrip() |
| 35 | swapcase() 将字符串中大写转换为小写,小写转换为大写 |
| 36 | title() 返回”标题化”的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle()) |
| 37 | translate(table, deletechars=””) 根据 str 给出的表(包含 256 个字符)转换 string 的字符, 要过滤掉的字符放到 deletechars 参数中 |
| 38 | upper() 转换字符串中的小写字母为大写 |
| 39 | zfill (width) 返回长度为 width 的字符串,原字符串右对齐,前面填充0 |
| 40 | isdecimal() 检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false。 |
函数示例
str = "this is string example from runoob....wow!!!"
print("str.capitalize() : ", str.capitalize())
# str.capitalize() : This is string example from runoob....wow!!!
str = "[runoob]"
print("str.center(40, '*') : ", str.center(40, '*'))
# str.center(40, '*') : ****************[runoob]****************
str = "www.runoob.com"
sub = 'o'
print("str.count('o') : ", str.count(sub))
# str.count('o') : 3
sub = 'run'
print("str.count('run', 0, 10) : ", str.count(sub, 0, 10))
# str.count('run', 0, 10) : 1
str = "菜鸟教程"
str_utf8 = str.encode("UTF-8")
str_gbk = str.encode("GBK")
print(str)
# 菜鸟教程
print("UTF-8 编码:", str_utf8)
# UTF-8 编码: b'\xe8\x8f\x9c\xe9\xb8\x9f\xe6\x95\x99\xe7\xa8\x8b'
print("GBK 编码:", str_gbk)
# GBK 编码: b'\xb2\xcb\xc4\xf1\xbd\xcc\xb3\xcc'
print("UTF-8 解码:", str_utf8.decode('UTF-8', 'strict'))
# UTF-8 解码: 菜鸟教程
print("GBK 解码:", str_gbk.decode('GBK', 'strict'))
# GBK 解码: 菜鸟教程
Str = 'Runoob example....wow!!!'
suffix = '!!'
print(Str.endswith(suffix))
# Ture
print(Str.endswith(suffix, 20))
# True
suffix = 'run'
print(Str.endswith(suffix))
# False
print(Str.endswith(suffix, 0, 19))
# False
str = "runoob\t12345\tabc"
print('原始字符串:', str)
# 原始字符串: runoob 12345 abc
# 默认 8 个空格
# runnob 有 6 个字符,后面的 \t 填充 2 个空格
# 12345 有 5 个字符,后面的 \t 填充 3 个空格
print('替换 \\t 符号:', str.expandtabs())
# 替换 \t 符号: runoob 12345 abc
# 2 个空格
# runnob 有 6 个字符,刚好是 2 的 3 倍,后面的 \t 填充 2 个空格
# 12345 有 5 个字符,不是 2 的倍数,后面的 \t 填充 1 个空格
print('使用 2 个空格替换 \\t 符号:', str.expandtabs(2))
# 使用 2 个空格替换 \t 符号: runoob 12345 abc
# 3 个空格
print('使用 3 个空格:', str.expandtabs(3))
# 使用 3 个空格: runoob 12345 abc
# 4 个空格
print('使用 4 个空格:', str.expandtabs(4))
# 使用 4 个空格: runoob 12345 abc
# 5 个空格
print('使用 5 个空格:', str.expandtabs(5))
# 使用 5 个空格: runoob 12345 abc
# 6 个空格
print('使用 6 个空格:', str.expandtabs(6))
# 使用 6 个空格: runoob 12345 abc
str1 = "Runoob example....wow!!!"
str2 = "exam"
print(str1.find(str2))
# 7
print(str1.find(str2, 5))
# 7
print(str1.find(str2, 10))
# -1
str1 = "Runoob example....wow!!!"
str2 = "exam"
print(str1.index(str2))
# 7
print(str1.index(str2, 5))
# 7
# print(str1.index(str2, 10)) # 异常
str = "runoob2016" # 字符串没有空格
print(str.isalnum())
# True
str = "www.runoob.com"
print(str.isalnum())
# False
str = "runoob"
print(str.isalpha())
# Ture
# 字母和中文文字
str = "runoob菜鸟教程"
print(str.isalpha())
# Ture
str = "Runoob example....wow!!!"
print(str.isalpha())
# False
str = "123456"
print(str.isdigit())
# True
str = "Runoob example....wow!!!"
print(str.isdigit())
# False
str = "RUNOOB example....wow!!!"
print(str.islower())
# False
str = "runoob example....wow!!!"
print(str.islower())
# True
str = "runoob2016"
print(str.isnumeric())
# False
str = "23443434"
print(str.isnumeric())
# True
str = " "
print(str.isspace())
# True
str = "Runoob example....wow!!!"
print(str.isspace())
# False
str = "This Is String Example...Wow!!!"
print(str.istitle())
# True
str = "This is string example....wow!!!"
print(str.istitle())
# False
str = "THIS IS STRING EXAMPLE....WOW!!!"
print(str.isupper())
# True
str = "THIS is string example....wow!!!"
print(str.isupper())
# False
s1 = "-"
s2 = ""
seq = ("r", "u", "n", "o", "o", "b") # 字符串序列
print(s1.join(seq))
# r-u-n-o-o-b
print(s2.join(seq))
# runoob
str = "runoob"
print(len(str)) # 字符串长度
# 6
l = [1, 2, 3, 4, 5]
print(len(l))
# 5
str = "Runoob example....wow!!!"
print(str.ljust(50, '*'))
# Runoob example....wow!!!**************************
str = "Runoob EXAMPLE....WOW!!!"
print(str.lower())
# runoob example....wow!!!
str = " this is string example....wow!!! ";
print(str.lstrip());
# this is string example....wow!!!
str = "88888888this is string example....wow!!!8888888";
print(str.lstrip('8'))
# this is string example....wow!!!8888888
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)
str = "this is string example....wow!!!"
print(str.translate(trantab))
# th3s 3s str3ng 2x1mpl2....w4w!!!
str = "runoob"
print("最大字符: " + max(str))
# 最大字符: u
str = "runoob";
print("最小字符: " + min(str));
# 最小字符: b
str = "www.w3cschool.cc"
print("菜鸟教程旧地址:", str)
# 菜鸟教程旧地址: www.w3cschool.cc
print("菜鸟教程新地址:", str.replace("w3cschool.cc", "runoob.com"))
# 菜鸟教程新地址: www.runoob.com
str = "this is string example....wow!!!"
print(str.replace("is", "was", 3))
# thwas was string example....wow!!!
str1 = "this is really a string example....wow!!!"
str2 = "is"
print(str1.rfind(str2))
# 5
print(str1.rfind(str2, 0, 10))
# 5
print(str1.rfind(str2, 10, 0))
# -1
print(str1.find(str2))
# 2
print(str1.find(str2, 0, 10))
# 2
print(str1.find(str2, 10, 0))
# -1
str1 = "this is really a string example....wow!!!"
str2 = "is"
print(str1.rindex(str2))
# 5
# print (str1.rindex(str2,10))
str = "this is string example....wow!!!"
print(str.rjust(50, '*'))
# ******************this is string example....wow!!!
str = " this is string example....wow!!! "
print(str.rstrip())
# this is string example....wow!!!
str = "*****this is string example....wow!!!*****"
print(str.rstrip('*'))
# *****this is string example....wow!!!
str = "this is string example....wow!!!"
print(str.split()) # 以空格为分隔符
# ['this', 'is', 'string', 'example....wow!!!']
print(str.split('i', 1)) # 以 i 为分隔符
# ['th', 's is string example....wow!!!']
print(str.split('w')) # 以 w 为分隔符
# ['this is string example....', 'o', '!!!']
txt = "Google#Runoob#Taobao#Facebook"
# 第二个参数为 1,返回两个参数列表
x = txt.split("#", 1)
print(x)
# ['Google', 'Runoob#Taobao#Facebook']
print('ab c\n\nde fg\rkl\r\n'.splitlines())
['ab c', '', 'de fg', 'kl']
print('ab c\n\nde fg\rkl\r\n'.splitlines(True))
# ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
str = "this is string example....wow!!!"
print(str.startswith('this')) # 字符串是否以 this 开头
# True
print(str.startswith('string', 8)) # 从第九个字符开始的字符串是否以 string 开头
# True
print(str.startswith('this', 2, 4)) # 从第2个字符开始到第四个字符结束的字符串是否以 this 开头
# False
str = "123abcrunoob321"
print(str.strip('12')) # 字符序列为 12
# 3abcrunoob3
str = "this is string example....wow!!!"
print(str.swapcase())
# THIS IS STRING EXAMPLE....WOW!!!
str = "This Is String Example....WOW!!!"
print(str.swapcase())
# tHIS iS sTRING eXAMPLE....wow!!!
str = "this is string example from runoob....wow!!!"
print(str.title())
# This Is String Example From Runoob....Wow!!!
txt = "hello b2b2b2 and 3g3g3g"
x = txt.title()
print(x) # 非字母后的第一个字母将转换为大写字母
# Hello B2B2B2 And 3G3G3G
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab) # 制作翻译表
str = "this is string example....wow!!!"
print(str.translate(trantab))
# th3s 3s str3ng 2x1mpl2....w4w!!!
str = "this is string example from runoob....wow!!!";
print("str.upper() : ", str.upper())
# str.upper() : THIS IS STRING EXAMPLE FROM RUNOOB....WOW!!!
str = "this is string example from runoob....wow!!!"
print("str.zfill : ", str.zfill(40))
# str.zfill : this is string example from runoob....wow!!!
print("str.zfill : ", str.zfill(50))
# str.zfill : 000000this is string example from runoob....wow!!!
str = "runoob2016"
print(str.isdecimal())
# False
str = "23443434"
print(str.isdecimal())
# True
'''
str.capitalize() : This is string example from runoob....wow!!!
str.center(40, '*') : ****************[runoob]****************
str.count('o') : 3
str.count('run', 0, 10) : 1
菜鸟教程
UTF-8 编码: b'\xe8\x8f\x9c\xe9\xb8\x9f\xe6\x95\x99\xe7\xa8\x8b'
GBK 编码: b'\xb2\xcb\xc4\xf1\xbd\xcc\xb3\xcc'
UTF-8 解码: 菜鸟教程
GBK 解码: 菜鸟教程
True
True
False
False
原始字符串: runoob 12345 abc
替换 \t 符号: runoob 12345 abc
使用 2 个空格替换 \t 符号: runoob 12345 abc
使用 3 个空格: runoob 12345 abc
使用 4 个空格: runoob 12345 abc
使用 5 个空格: runoob 12345 abc
使用 6 个空格: runoob 12345 abc
7
7
-1
7
7
True
False
True
True
False
True
False
False
True
False
True
True
False
True
False
True
False
r-u-n-o-o-b
runoob
6
5
Runoob example....wow!!!**************************
runoob example....wow!!!
this is string example....wow!!!
this is string example....wow!!!8888888
th3s 3s str3ng 2x1mpl2....w4w!!!
最大字符: u
最小字符: b
菜鸟教程旧地址: www.w3cschool.cc
菜鸟教程新地址: www.runoob.com
thwas was string example....wow!!!
5
5
-1
2
2
-1
5
******************this is string example....wow!!!
this is string example....wow!!!
*****this is string example....wow!!!
['this', 'is', 'string', 'example....wow!!!']
['th', 's is string example....wow!!!']
['this is string example....', 'o', '!!!']
['Google', 'Runoob#Taobao#Facebook']
['ab c', '', 'de fg', 'kl']
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
True
True
False
3abcrunoob3
THIS IS STRING EXAMPLE....WOW!!!
tHIS iS sTRING eXAMPLE....wow!!!
This Is String Example From Runoob....Wow!!!
Hello B2B2B2 And 3G3G3G
th3s 3s str3ng 2x1mpl2....w4w!!!
str.upper() : THIS IS STRING EXAMPLE FROM RUNOOB....WOW!!!
str.zfill : this is string example from runoob....wow!!!
str.zfill : 000000this is string example from runoob....wow!!!
False
True
'''
列表
- 索引截取方式与元组相同
- 截取后成为一个新列表
- 元素在打方括号中,以逗号分隔
- 列表的元素可改变
- 元素可以是元组
list = ['test', 1, 1.2, 999]
list2 = [1, 'test']
print(list) # 输出完整列表
# ['test', 1, 1.2, 999]
print(list[0]) # 输出列表第一个元素
# test
print(list[1:3]) # 从第二个开始输出到第三个元素
# [1, 1.2]
print(list[2:]) # 输出从第三个元素开始的所有元素
# [1.2, 999]
print(list2 * 2) # 输出两次列表
# [1, 'test', 1, 'test']
print(list + list2) # 连接列表
# ['test', 1, 1.2, 999, 1, 'test']
list3 = [1, 2, 3, 4, 5]
print(list3)
# [1, 2, 3, 4, 5]
list3[0] = 'test' # 修改第一元素
print(list3)
# ['test', 2, 3, 4, 5]
list3[2:4] = [22, 33] # 修改第三个到第四元素
print(list3)
# ['test', 2, 22, 33, 5]
list4 = [1, 2, 3, 4, 5]
print(list4)
# [1, 2, 3, 4, 5]
print(list4[-1::-1])
[5, 4, 3, 2, 1]
# 第一个-1表示从最后一个开始
# 中间为空表示移动到列表末,最后一个-1为步长,-表示逆向
print(list4[-2:0:-1])
# [4, 3, 2]
print(list4[-1::])
# [5]
'''
['test', 1, 1.2, 999]
test
[1, 1.2]
[1.2, 999]
[1, 'test', 1, 'test']
['test', 1, 1.2, 999, 1, 'test']
[1, 2, 3, 4, 5]
['test', 2, 3, 4, 5]
['test', 2, 22, 33, 5]
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
[4, 3, 2]
[5]
'''
更新和删除元素
list5 = [1, 3, 5, 'test']
print(list5)
list5.append('restart')
print(list5) # 在末尾添加元素
del list5[2] # 删除第三个元素
print(list5)
'''
[1, 3, 5, 'test']
[1, 3, 5, 'test', 'restart']
[1, 3, 'test', 'restart']
'''
列表脚本操作符
list6 = [1, 2, 3, 'test']
print(list6)
print(len(list6)) # 列表长度
print([1, 2, 3] + [4, 5, 6]) # 组合
print(['test'] * 4) # 重复
print(3 in [1, 2, 3]) # 存在与否
for x in [1, 2, 3]:
print(x, end=" ")
# 迭代
'''
[1, 2, 3, 'test']
4
[1, 2, 3, 4, 5, 6]
['test', 'test', 'test', 'test']
True
1 2 3
'''
镶嵌列表
# 镶嵌列表
a = ['a', 'b', 'c']
n = [1, 2, 3]
x = [a, n]
print(x)
print(x[0])
print(x[0][1])
'''
[['a', 'b', 'c'], [1, 2, 3]]
['a', 'b', 'c']
b
'''
函数
| 序号 | 函数 |
|---|---|
| 1 | len(list) 列表元素个数 |
| 2 | max(list) 返回列表元素最大值 |
| 3 | min(list) 返回列表元素最小值 |
| 4 | list(seq) 将元组转换为列表 |
| 序号 | 方法 |
|---|---|
| 1 | list.append(obj) 在列表末尾添加新的对象 |
| 2 | list.count(obj) 统计某个元素在列表中出现的次数 |
| 3 | list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) |
| 4 | list.index(obj) 从列表中找出某个值第一个匹配项的索引位置 |
| 5 | list.insert(index, obj) 将对象插入列表 |
| 6 | [list.pop(index=-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 |
| 7 | list.remove(obj) 移除列表中某个值的第一个匹配项 |
| 8 | list.reverse() 反向列表中元素 |
| 9 | list.sort( key=None, reverse=False) 对原列表进行排序 |
| 10 | list.clear() 清空列表 |
| 11 | list.copy() 复制列表 |
函数示例
list1 = ['Google', 'Runoob', 'Taobao']
print(len(list1))
# 3
list2 = list(range(5)) # 创建一个 0-4 的列表
print(len(list2))
# 5
list1, list2 = ['Google', 'Runoob', 'Taobao'], [456, 700, 200]
print("list1 最大元素值 : ", max(list1))
# list1 最大元素值 : Taobao
print("list2 最大元素值 : ", max(list2))
# list2 最大元素值 : 700
list1, list2 = ['Google', 'Runoob', 'Taobao'], [456, 700, 200]
print("list1 最小元素值 : ", min(list1))
# list1 最小元素值 : Google
print("list2 最小元素值 : ", min(list2))
# list2 最小元素值 : 200
aTuple = (123, 'Google', 'Runoob', 'Taobao')
list1 = list(aTuple)
print("列表元素 : ", list1)
# 列表元素 : [123, 'Google', 'Runoob', 'Taobao']
str = "Hello World"
list2 = list(str)
print("列表元素 : ", list2)
# 列表元素 : ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
list1 = ['Google', 'Runoob', 'Taobao']
list1.append('Baidu')
print("更新后的列表 : ", list1)
# 更新后的列表 : ['Google', 'Runoob', 'Taobao', 'Baidu']
aList = [123, 'Google', 'Runoob', 'Taobao', 123];
print("123 元素个数 : ", aList.count(123))
# 123 元素个数 : 2
print("Runoob 元素个数 : ", aList.count('Runoob'))
# Runoob 元素个数 : 1
list1 = ['Google', 'Runoob', 'Taobao']
list2 = list(range(5)) # 创建 0-4 的列表
list1.extend(list2) # 扩展列表
print("扩展后的列表:", list1)
# 扩展后的列表: ['Google', 'Runoob', 'Taobao', 0, 1, 2, 3, 4]
list1 = ['Google', 'Runoob', 'Taobao']
print('Runoob 索引值为', list1.index('Runoob'))
# Runoob 索引值为 1
print('Taobao 索引值为', list1.index('Taobao'))
# Taobao 索引值为 2
list1 = ['Google', 'Runoob', 'Taobao']
list1.insert(1, 'Baidu')
print('列表插入元素后为 : ', list1)
# 列表插入元素后为 : ['Google', 'Baidu', 'Runoob', 'Taobao']
list1 = ['Google', 'Runoob', 'Taobao']
list1.pop()
print("列表现在为 : ", list1)
# 列表现在为 : ['Google', 'Runoob']
list1.pop(1)
print("列表现在为 : ", list1)
# 列表现在为 : ['Google']
list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list1.remove('Taobao')
print("列表现在为 : ", list1)
# 列表现在为 : ['Google', 'Runoob', 'Baidu']
list1.remove('Baidu')
print("列表现在为 : ", list1)
# 列表现在为 : ['Google', 'Runoob']
list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list1.reverse()
print("列表反转后: ", list1)
# 列表反转后: ['Baidu', 'Taobao', 'Runoob', 'Google']
aList = ['Google', 'Runoob', 'Taobao', 'Facebook']
aList.sort()
print("List : ", aList)
# List : ['Facebook', 'Google', 'Runoob', 'Taobao']
list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list1.clear()
print("列表清空后 : ", list1)
# 列表清空后 : []
list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list2 = list1.copy()
print("list2 列表: ", list2)
# list2 列表: ['Google', 'Runoob', 'Taobao', 'Baidu']
'''
3
5
list1 最大元素值 : Taobao
list2 最大元素值 : 700
list1 最小元素值 : Google
list2 最小元素值 : 200
列表元素 : [123, 'Google', 'Runoob', 'Taobao']
列表元素 : ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
更新后的列表 : ['Google', 'Runoob', 'Taobao', 'Baidu']
123 元素个数 : 2
Runoob 元素个数 : 1
扩展后的列表: ['Google', 'Runoob', 'Taobao', 0, 1, 2, 3, 4]
Runoob 索引值为 1
Taobao 索引值为 2
列表插入元素后为 : ['Google', 'Baidu', 'Runoob', 'Taobao']
列表现在为 : ['Google', 'Runoob']
列表现在为 : ['Google']
列表现在为 : ['Google', 'Runoob', 'Baidu']
列表现在为 : ['Google', 'Runoob']
列表反转后: ['Baidu', 'Taobao', 'Runoob', 'Google']
List : ['Facebook', 'Google', 'Runoob', 'Taobao']
列表清空后 : []
list2 列表: ['Google', 'Runoob', 'Taobao', 'Baidu']
'''
元组
- 元组元素不能更改
- 元组写在小括号内,以
,分隔 - 各元素类型可以不同
- 元组的索引切片操作与string一样
tuple = (1, 1.2, 'test', 'dou')
tuple2 = (1, 'test2')
tuple3 = (1,) # 单个元素后面加逗号
tuple4 = () # 空元组
print(tuple4)
# ()
print(tuple)
# (1, 1.2, 'test', 'dou')
print(tuple3)
# (1,)
print(tuple[0]) # 输出第一个元素
# 1
print(tuple[1:3]) # 输出第二个到第三个元素
# (1.2, 'test')
print(tuple[0:]) # 输出所有元素
# (1, 1.2, 'test', 'dou')
print(tuple[:]) # 输出所有元素
# (1, 1.2, 'test', 'dou')
print(tuple[:3]) # 输出第三个及前面的所有
# (1, 1.2, 'test')
print(tuple * 2)
# (1, 1.2, 'test', 'dou', 1, 1.2, 'test', 'dou')
print(tuple + tuple2)
# (1, 1.2, 'test', 'dou', 1, 'test2')
'''
()
(1, 1.2, 'test', 'dou')
(1,)
1
(1.2, 'test')
(1, 1.2, 'test', 'dou')
(1, 1.2, 'test', 'dou')
(1, 1.2, 'test')
(1, 1.2, 'test', 'dou', 1, 1.2, 'test', 'dou')
(1, 1.2, 'test', 'dou', 1, 'test2')
'''
运算符
tuple6 = (1, 2, 3, 'test')
print(tuple6)
print(len(tuple6)) # 列表长度
print((1, 2, 3) + (4, 5, 6)) # 组合
print(('test',) * 4) # 重复
print(3 in (1, 2, 3)) # 存在与否
for x in (1, 2, 3):
print(x, end=' ')
# 迭代
'''
(1, 2, 3, 'test')
4
(1, 2, 3, 4, 5, 6)
('test', 'test', 'test', 'test')
True
1 2 3
'''
函数
| 序号 | 方法及描述 | 实例 |
|---|---|---|
| 1 | len(tuple) 计算元组元素个数。 | >>> tuple1 = ('Google', 'Runoob', 'Taobao') >>> len(tuple1) 3 |
| 2 | max(tuple) 返回元组中元素最大值。 | >>> tuple2 = ('5', '4', '8') >>> max(tuple2) '8' |
| 3 | min(tuple) 返回元组中元素最小值。 | >>> tuple2 = ('5', '4', '8') >>> min(tuple2) '4' |
| 4 | tuple(iterable) 将可迭代系列转换为元组。 | >>> list1= ['Google', 'Taobao', 'Runoob', 'Baidu'] >>> tuple1=tuple(list1) >>> tuple1 ('Google', 'Taobao', 'Runoob', 'Baidu') |
字典
- 字典是无序的,依靠键值对来存取
- 字典用
{}标识,键(key) : 值(value) key不可变,并且是唯一的- 使用
{}创建空字典 - 键必须不可变,所以可以用数字,字符串或元组充当,而用列表就不行
dict = {} # 空字典
dict[2] = 'test'
dict['test'] = 1
print(dict)
# {2: 'test', 'test': 1}
dict2 = {'test': 1, 1: 'dddd'}
print(dict2)
# {'test': 1, 1: 'dddd'}
print(dict[2], dict['test']) # 输出2,test的值
# test 1
print(dict2.keys()) # 输出所有键名
# dict_keys(['test', 1])
print(dict2.values()) # 输出所有键值
# dict_values([1, 'dddd'])
dict['test'] = 'txt' # 修改键值
print(dict)
# {2: 'test', 'test': 'txt'}
del dict2[1] # 删除一个键
print(dict2)
# {'test': 1}
dict2.clear() # 清空字典
print(dict2)
# {}
del dict2 # 删除字典
dict2 = {'1': 2, 'var': 'str', 'test': 'test', 'var': 'var'}
# 重复时后者覆盖前者
print(dict2)
# {'1': 2, 'var': 'var', 'test': 'test'}
'''
{2: 'test', 'test': 1}
{'test': 1, 1: 'dddd'}
test 1
dict_keys(['test', 1])
dict_values([1, 'dddd'])
{2: 'test', 'test': 'txt'}
{'test': 1}
{}
{'1': 2, 'var': 'var', 'test': 'test'}
'''
函数
| 序号 | 函数及描述 | 实例 |
|---|---|---|
| 1 | len(dict) 计算字典元素个数,即键的总数。 | >>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} >>> len(dict) 3 |
| 2 | str(dict) 输出字典,可以打印的字符串表示。 | >>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} >>> str(dict) "{'Name': 'Runoob', 'Class': 'First', 'Age': 7}" |
| 3 | type(variable) 返回输入的变量类型,如果变量是字典就返回字典类型。 | >>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} >>> type(dict) <class 'dict'> |
| 序号 | 函数及描述 |
|---|---|
| 1 | radiansdict.clear() 删除字典内所有元素 |
| 2 | radiansdict.copy() 返回一个字典的浅复制 |
| 3 | radiansdict.fromkeys() 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值 |
| 4 | radiansdict.get(key, default=None) 返回指定键的值,如果键不在字典中返回 default 设置的默认值 |
| 5 | key in dict 如果键在字典dict里返回true,否则返回false |
| 6 | radiansdict.items() 以列表返回一个视图对象 |
| 7 | radiansdict.keys() 返回一个视图对象 |
| 8 | radiansdict.setdefault(key, default=None) 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default |
| 9 | radiansdict.update(dict2) 把字典dict2的键/值对更新到dict里 |
| 10 | radiansdict.values() 返回一个视图对象 |
| 11 | [pop(key,default]) 删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。 |
| 12 | popitem() 随机返回并删除字典中的最后一对键和值。 |
函数示例
dict = {'Name': 'Zara', 'Age': 7}
print ("字典长度 : %d" % len(dict))
# 字典长度 : 2
dict.clear()
print ("字典删除后长度 : %d" % len(dict))
# 字典删除后长度 : 0
dict1 = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
dict2 = dict1.copy()
print("新复制的字典为 : ", dict2)
# 新复制的字典为 : {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq)
print("新的字典为 : %s" % str(dict))
# 新的字典为 : {'name': None, 'age': None, 'sex': None}
dict = dict.fromkeys(seq, 10)
print("新的字典为 : %s" % str(dict))
# 新的字典为 : {'name': 10, 'age': 10, 'sex': 10}
dict = {'Name': 'Runoob', 'Age': 27}
print ("Age 值为 : %s" % dict.get('Age'))
# Age 值为 : 27
print ("Sex 值为 : %s" % dict.get('Sex', "NA"))
# Sex 值为 : NA
dict = {'Name': 'Runoob', 'Age': 7}
# 检测键 Age 是否存在
if 'Age' in dict:
print("键 Age 存在")
else:
print("键 Age 不存在")
# 键 Age 存在
# 检测键 Sex 是否存在
if 'Sex' in dict:
print("键 Sex 存在")
else:
print("键 Sex 不存在")
# 键 Sex 不存在
# not in
# 检测键 Age 是否存在
if 'Age' not in dict:
print("键 Age 不存在")
else:
print("键 Age 存在")
# 键 Age 存在
dict = {'Name': 'Runoob', 'Age': 7}
print("Value : %s" % dict.items())
# Value : dict_items([('Name', 'Runoob'), ('Age', 7)])
dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
keys = dishes.keys()
values = dishes.values()
# 迭代
n = 0
for val in values:
n += val
print(n)
# 504
# keys 和 values 以相同顺序(插入顺序)进行迭代
print(list(keys)) # 使用 list() 转换为列表
# ['eggs', 'sausage', 'bacon', 'spam']
print(list(values))
# [2, 1, 1, 500]
# 视图对象是动态的,受字典变化的影响,以下删除了字典的 key,视图对象转为列表后也跟着变化
del dishes['eggs']
del dishes['sausage']
print(list(keys))
# ['bacon', 'spam']
dict = {'Name': 'Runoob', 'Age': 7}
print("Age 键的值为 : %s" % dict.setdefault('Age', None))
# Age 键的值为 : 7
print("Sex 键的值为 : %s" % dict.setdefault('Sex', None))
# Sex 键的值为 : None
print("新字典为:", dict)
# 新字典为: {'Name': 'Runoob', 'Age': 7, 'Sex': None}
dict = {'Name': 'Runoob', 'Age': 7}
dict2 = {'Sex': 'female'}
dict.update(dict2)
print("更新字典 dict : ", dict)
# 更新字典 dict : {'Name': 'Runoob', 'Age': 7, 'Sex': 'female'}
site= {'name': '菜鸟教程', 'alexa': 10000, 'url': 'www.runoob.com'}
pop_obj=site.pop('name')
print(pop_obj)
# 菜鸟教程
site= {'name': '菜鸟教程', 'alexa': 10000, 'url': 'www.runoob.com'}
pop_obj=site.popitem()
print(pop_obj)
# ('url', 'www.runoob.com')
print(site)
# {'name': '菜鸟教程', 'alexa': 10000}
'''
字典长度 : 2
字典删除后长度 : 0
新复制的字典为 : {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
新的字典为 : {'name': None, 'age': None, 'sex': None}
新的字典为 : {'name': 10, 'age': 10, 'sex': 10}
Age 值为 : 27
Sex 值为 : NA
键 Age 存在
键 Sex 不存在
键 Age 存在
Value : dict_items([('Name', 'Runoob'), ('Age', 7)])
504
['eggs', 'sausage', 'bacon', 'spam']
[2, 1, 1, 500]
['bacon', 'spam']
Age 键的值为 : 7
Sex 键的值为 : None
新字典为: {'Name': 'Runoob', 'Age': 7, 'Sex': None}
更新字典 dict : {'Name': 'Runoob', 'Age': 7, 'Sex': 'female'}
菜鸟教程
('url', 'www.runoob.com')
{'name': '菜鸟教程', 'alexa': 10000}
'''
集合
创建格式
parame = {value1, value2, ……}
or
set(value)
set() # 创建一个空集合
sites = {1, 'test', '123'}
print(sites) # 输出集合,重复的元素被自动去掉
# {1, '123', 'test'}
# 成员测试
if 'test' in sites:
print('test 在集合中')
else:
print('test 不在集合中')
# set可以进行集合运算
a = set('abracadabra')
b = set('alacazam')
print(a)
print(a - b) # a 和 b 的差集
print(a | b) # a 和 b 的并集
print(a & b) # a 和 b 的交集
print(a ^ b) # a 和 b 中不同时存在的元素
'''
{1, '123', 'test'}
test 在集合中
{'a', 'b', 'r', 'c', 'd'}
{'b', 'd', 'r'}
{'a', 'm', 'r', 'b', 'c', 'd', 'l', 'z'}
{'c', 'a'}
{'d', 'l', 'r', 'm', 'z', 'b'}
'''
推导式
a = {x for x in 'abracadabra' if x not in 'abc'}
print(a)
# {'r', 'd'}
基本操作
添加元素
s.add( x )
thisset = set(("Google", "Runoob", "Taobao"))
print(thisset)
thisset.add('test')
print(thisset)
'''
{'Taobao', 'Google', 'Runoob'}
{'Taobao', 'test', 'Google', 'Runoob'}
'''
s.update( x )参数可以是列表,元组,字典
s.update( x )
thisset = set(("Google", "Runoob", "Taobao"))
thisset.update({1, 3})
print(thisset)
thisset.update([1, 4], [5, 6])
print(thisset)
'''
{1, 3, 'Google', 'Taobao', 'Runoob'}
{1, 3, 4, 'Google', 5, 6, 'Taobao', 'Runoob'}
'''
移除元素
s.remove( x )
thisset = set(("Google", "Runoob", "Taobao"))
print(thisset)
thisset.remove("Taobao")
print(thisset)
'''
{'Google', 'Taobao', 'Runoob'}
{'Google', 'Runoob'}
'''
s.discard( x )
thisset = set(("Google", "Runoob", "Taobao"))
print(thisset)
thisset.discard("Facebook") # 不存在不会发生错误
print(thisset)
'''
{'Google', 'Taobao', 'Runoob'}
{'Google', 'Taobao', 'Runoob'}
'''
设置随机删除集合中的一个元素
pop 方法会对集合进行无序的排列
s.pop()
thisset = set(("Google", "Runoob", "Taobao", "Facebook"))
x = thisset.pop()
print(x)
'''
Facebook
'''
计算集合元素个数
len(s)
thisset = set(("Google", "Runoob", "Taobao"))
print(len(thisset))
# 3
清空集合
s.clear()
thisset = set(("Google", "Runoob", "Taobao"))
thisset.clear()
print(thisset)
# set()
判断元素是否在集合中存在
x in s
thisset = set(("Google", "Runoob", "Taobao"))
print("Runoob" in thisset)
print("Facebook" in thisset)
'''
True
False
'''
判断元素 x 是否在集合 s 中,存在返回 True,不存在返回 False
| 方法 | 描述 |
|---|---|
| add() | 为集合添加元素 |
| clear() | 移除集合中的所有元素 |
| copy() | 拷贝一个集合 |
| difference() | 返回多个集合的差集 |
| difference_update() | 移除集合中的元素,该元素在指定的集合也存在。 |
| discard() | 删除集合中指定的元素 |
| intersection() | 返回集合的交集 |
| intersection_update() | 返回集合的交集。 |
| isdisjoint() | 判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。 |
| issubset() | 判断指定集合是否为该方法参数集合的子集。 |
| issuperset() | 判断该方法的参数集合是否为指定集合的子集 |
| pop() | 随机移除元素 |
| remove() | 移除指定元素 |
| symmetric_difference() | 返回两个集合中不重复的元素集合。 |
| symmetric_difference_update() | 移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中。 |
| union() | 返回两个集合的并集 |
| update() | 给集合添加元素 |
函数示例
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
print(fruits)
# {'apple', 'cherry', 'banana', 'orange'}
fruits = {"apple", "banana", "cherry"}
fruits.clear()
print(fruits)
# set()
fruits = {"apple", "banana", "cherry"}
x = fruits.copy()
print(x)
# {'apple', 'cherry', 'banana'}
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.difference(y)
print(z)
# {'cherry', 'banana'}
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.difference_update(y)
print(x)
# {'cherry', 'banana'}
fruits = {"apple", "banana", "cherry"}
fruits.discard("banana")
print(fruits)
# {'apple', 'cherry'}
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
z = x.intersection(y)
print(z)
# {'apple'}
x = {"apple", "banana", "cherry"} # y 集合不包含 banana 和 cherry,被移除
y = {"google", "runoob", "apple"}
x.intersection_update(y)
print(x)
# {'apple'}
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "facebook"}
z = x.isdisjoint(y)
print(z)
# True
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
z = x.issubset(y)
print(z)
# True
x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"}
z = x.issuperset(y)
print(z)
# True
fruits = {"apple", "banana", "cherry"}
fruits.pop()
print(fruits)
# {'cherry', 'banana'}
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)
# {'apple', 'cherry'}
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
z = x.symmetric_difference(y)
print(z)
# {'cherry', 'runoob', 'banana', 'google'}
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
x.symmetric_difference_update(y)
print(x)
# {'cherry', 'runoob', 'banana', 'google'}
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
z = x.union(y)
print(z)
# {'apple', 'cherry', 'banana', 'google', 'runoob'}
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
x.update(y)
print(x)
# {'apple', 'cherry', 'banana', 'google', 'runoob'}
'''
{'orange', 'apple', 'cherry', 'banana'}
set()
{'apple', 'cherry', 'banana'}
{'cherry', 'banana'}
{'cherry', 'banana'}
{'apple', 'cherry'}
{'apple'}
{'apple'}
True
True
True
{'cherry', 'banana'}
{'apple', 'cherry'}
{'cherry', 'banana', 'runoob', 'google'}
{'cherry', 'google', 'banana', 'runoob'}
{'cherry', 'banana', 'google', 'apple', 'runoob'}
{'cherry', 'banana', 'google', 'apple', 'runoob'}
'''
条件控制
if语句
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
'''
如果 "condition_1" 为 True 将执行 "statement_block_1" 块语句
如果 "condition_1" 为False,将判断 "condition_2"
如果"condition_2" 为 True 将执行 "statement_block_2" 块语句
如果 "condition_2" 为False,将执行"statement_block_3"块语句
'''
- python每个条件后面都要使用冒号,接着是执行语句
- 缩进相同的作为语句块,缩进为一个tab
- python中没有switch-case语句
age = int(input("请输入你家狗狗的年龄: "))
print("")
if age <= 0:
print("你是在逗我吧!")
elif age == 1:
print("相当于 14 岁的人。")
elif age == 2:
print("相当于 22 岁的人。")
elif age > 2:
human = 22 + (age - 2) * 5
print("对应人类年龄: ", human)
# 退出提示
input("点击 enter 键退出")
'''
请输入你家狗狗的年龄: 3
对应人类年龄: 27
点击 enter 键退出
'''
if嵌套
if 表达式1:
语句
if 表达式2:
语句
elif 表达式3:
语句
else:
语句
elif 表达式4:
语句
else:
语句
num = int(input("输入一个数字:"))
if num % 2 == 0:
if num % 3 == 0:
print("你输入的数字可以整除 2 和 3")
else:
print("你输入的数字可以整除 2,但不能整除 3")
else:
if num % 3 == 0:
print("你输入的数字可以整除 3,但不能整除 2")
else:
print("你输入的数字不能整除 2 和 3")
'''
输入一个数字:4
你输入的数字可以整除 2,但不能整除 3
'''
循环语句
- python中循环有for和while
- 缩进和冒号和条件控制相似
while循环
while 判断条件(condition):
执行语句(statements)……
n = 10
i = 0
sum = 0
while i <= n:
sum = sum + i
i +=1
print(sum)
'''
55
'''
无限循环
while 1 == 1:
print('随便输入,输入0退出')
var = int(input())
if var == 0:
exit() # break
while 1: print('1')
while-else
while <expr>:
<statement(s)>
else:
<additional_statement(s)>
count = 0
while count < 5:
print (count, " 小于 5")
count = count + 1
else:
print (count, " 大于或等于 5")
for语句
for <variable> in <sequence>:
<statements>
else:
<statements>
sites = ["Baidu", "Google", "Runoob", "Taobao"]
for site in sites:
if site == "Runoob":
print("菜鸟教程!")
break
print("循环数据 " + site)
else:
print("没有循环数据!")
print("完成循环!")
range函数
for i in range(0, 3):
print(i)
for i in range(5, 6):
print(i)
for i in range(1, 10, 3):
print(i)
for i in range(-10, -100, -40):
print(i)
a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ']
for i in range(len(a)):
print(i, a[i])
print(list(range(5)))
'''
0
1
2
5
1
4
7
-10
-50
-90
0 Google
1 Baidu
2 Runoob
3 Taobao
4 QQ
[0, 1, 2, 3, 4]
'''
break和continue
n = 5
while n > 0:
n -= 1
if n == 2:
break
print(n)
print('循环结束。')
n = 5
while n > 0:
n -= 1
if n == 2:
continue
print(n)
print('循环结束。')
'''
4
3
循环结束。
4
3
1
0
循环结束。
'''
for-else
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, '等于', x, '*', n//x)
break # 直接跳出第一个循环,不执行else
else:
# 循环中没有找到元素
print(n, ' 是质数')
'''
2 是质数
3 是质数
4 等于 2 * 2
5 是质数
6 等于 2 * 3
7 是质数
8 等于 2 * 4
9 等于 3 * 3
'''
pass语句
for letter in 'Runoob':
if letter == 'o':
pass
print('执行 pass 块')
print('当前字母 :', letter)
print("Good bye!")
'''
当前字母 : R
当前字母 : u
当前字母 : n
执行 pass 块
当前字母 : o
执行 pass 块
当前字母 : o
当前字母 : b
Good bye!
'''
pass 不做任何事情,一般用做占位语句
迭代器和生成器
迭代器
迭代器两个基本函数iter() next()
list = [1, 2, 3, 4]
it = iter(list) # 创建迭代器对象
print(next(it)) # 输出迭代器的下一个元素
# 1
print(next(it))
# 2
list = [1, 2, 3, 4]
it = iter(list) # 创建迭代器对象
for x in it:
print(x, end=" ")
# 1 2 3 4
list = [1, 2, 3, 4]
it = iter(list) # 创建迭代器对象
while True:
try:
print(next(it))
except StopIteration:
exit()
'''
1
2
3
4
'''
'''
1
2
1 2 3 4 1
2
3
4
'''
创建一个迭代器
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
'''
1
2
3
4
5
'''
StopIteration
StopIteration 异常用于标识迭代的完成,防止出现无限循环的情况
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)
生成器
使用yield()函数
def fibonacci(n): # 生成器函数 - 斐波那契
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
while True:
try:
print (next(f), end=" ")
except StopIteration:
exit()
'''
0 1 1 2 3 5 8 13 21 34 55
'''
函数
- 函数代码块以def关键字开头,厚街函数标识符名称和圆括号()
- 传入的参数和自变量放在圆括号内
- 函数内容以冒号起始,并且缩进
- return [表达式] 结束函数并返回值
# 计算面积函数
def area(width, height):
return width * height
def print_welcome(name):
print("Welcome", name)
print_welcome("Runoob")
w = 4
h = 5
print("width =", w, " height =", h, " area =", area(w, h))
函数调用
print_welcome("Runoob")
area(w, h)
exit()
参数传递
不可变类型
number,string,tuples
- 先赋值
a = 2,再赋值a = 5,后者覆盖前者,相当于新生成一个值,地址变了 - 传递的参数值不会影响原值,函数内部重新赋值会生成一个的对象,不会影响函数外的值
def change(a):
print(id(a)) # 指向的是同一个对象
a=10
print(id(a)) # 一个新对象
a=1
print(id(a))
change(a)
'''
140721657271968-
140721657271968
140721657272256
'''
可变类型
list,dictionary,set
- 列表赋值,然后再修改元素,列表地址不会改变,还是原来那个列表
- 传入函数的这类参数,在函数内修改会影响到函数外的值
# 可写函数说明
def changeme(mylist):
"""修改传入的列表"""
mylist.append([1, 2, 3, 4])
print("函数内取值: ", mylist)
return
# 调用changeme函数
mylist = [10, 20, 30]
changeme(mylist)
print("函数外取值: ", mylist)
'''
函数内取值: [10, 20, 30, [1, 2, 3, 4]]
函数外取值: [10, 20, 30, [1, 2, 3, 4]]
'''
参数
必需参数
必需参数须以正确的顺序传入函数。调用时的数量必须和声明时的一样
#可写函数说明
def printme( str ):
"打印任何传入的字符串"
print (str)
return
# 调用 printme 函数,不加参数会报错
str = 'test'
printme(str)
关键字参数
关键字参数和函数调用关系紧密,函数调用使用关键字参数来确定传入的参数值,使用关键字参数允许函数调用时参数的顺序与声明时不一致,因为 Python 解释器能够用参数名匹配参数值。
#可写函数说明
def printinfo( name, age ):
"打印任何传入的字符串"
print ("名字: ", name)
print ("年龄: ", age)
return
#调用printinfo函数
printinfo( age=50, name="runoob" )
默认参数
调用函数时,如果没有传递参数,则会使用默认参数。
#可写函数说明
def printinfo( name, age = 35 ):
"打印任何传入的字符串"
print ("名字: ", name)
print ("年龄: ", age)
return
#调用printinfo函数
printinfo( age=50, name="runoob" )
print ("------------------------")
printinfo( name="runoob" )
'''
名字: runoob
年龄: 50
------------------------
名字: runoob
年龄: 35
'''
不定长参数
def functionname([formal_args,] *var_args_tuple ):
"函数_文档字符串"
function_suite
return [expression]
def functionname([formal_args,] **var_args_dict ):
"函数_文档字符串"
function_suite
return [expression]
- 加了星号 ***** 的参数会以元组(tuple)的形式导入,存放所有未命名的变量参数
- 在函数调用时没有指定参数,它就是一个空元组
- 加了两个星号 ** 的参数会以字典的形式导入
- 如果单独出现星号 ***** 后的参数必须用关键字传入
# 可写函数说明
def printinfo( arg1, *vartuple ):
"打印任何传入的参数"
print ("输出: ")
print (arg1)
for var in vartuple:
print (var)
return
# 调用printinfo 函数
printinfo( 10 )
printinfo( 70, 60, 50 )
'''
输出:
10
输出:
70
60
50
'''
# 可写函数说明
def printinfo( arg1, **vardict ):
"打印任何传入的参数"
print ("输出: ")
print (arg1)
print (vardict)
# 调用printinfo 函数
printinfo(1, a=2,b=3)
'''
输出:
1
{'a': 2, 'b': 3}
'''
匿名函数
- 使用 lambda 来创建匿名函数
- lambda的主体是一个表达式,而不是一个代码块
- lambda 函数拥有自己的命名空间,且不能访问自己参数列表之外或全局命名空间里的参数
lambda [arg1 [,arg2,.....argn]]:expression
# 可写函数说明
sum = lambda arg1, arg2: arg1 + arg2
# 调用sum函数
print ("相加后的值为 : ", sum( 10, 20 ))
print ("相加后的值为 : ", sum( 20, 20 ))
'''
相加后的值为 : 30
相加后的值为 : 40
'''
return语句
return [表达式] 语句用于退出函数,选择性地向调用方返回一个表达式
# 可写函数说明
def sum( arg1, arg2 ):
# 返回2个参数的和."
total = arg1 + arg2
print ("函数内 : ", total)
return total
# 调用sum函数
total = sum( 10, 20 )
print ("函数外 : ", total)
'''
函数内 : 30
函数外 : 30
'''
强制位置参数
函数形参语法 / 用来指明函数形参必须使用指定位置参数,不能使用关键字参数的形式。
形参 a 和 b 必须使用指定位置参数,c 或 d 可以是位置形参或关键字形参,而 e 和 f 要求为关键字形参
def f(a, b, /, c, d, *, e, f):
print(a, b, c, d, e, f)
f(10, 20, 30, d=40, e=50, f=60)
'''
10 20 30 40 50 60
'''
数据结构
列表
| 方法 | 描述 |
|---|---|
| list.append(x) | 把一个元素添加到列表的结尾,相当于 a[len(a):] = [x]。 |
| list.extend(L) | 通过添加指定列表的所有元素来扩充列表,相当于 a[len(a):] = L。 |
| list.insert(i, x) | 在指定位置插入一个元素。第一个参数是准备插入到其前面的那个元素的索引,例如 a.insert(0, x) 会插入到整个列表之前,而 a.insert(len(a), x) 相当于 a.append(x) 。 |
| list.remove(x) | 删除列表中值为 x 的第一个元素。如果没有这样的元素,就会返回一个错误。 |
| list.pop([i]) | 从列表的指定位置移除元素,并将其返回。如果没有指定索引,a.pop()返回最后一个元素。元素随即从列表中被移除。(方法中 i 两边的方括号表示这个参数是可选的,而不是要求你输入一对方括号,你会经常在 Python 库参考手册中遇到这样的标记。) |
| list.clear() | 移除列表中的所有项,等于del a[:]。 |
| list.index(x) | 返回列表中第一个值为 x 的元素的索引。如果没有匹配的元素就会返回一个错误。 |
| list.count(x) | 返回 x 在列表中出现的次数。 |
| list.sort() | 对列表中的元素进行排序。 |
| list.reverse() | 倒排列表中的元素。 |
| list.copy() | 返回列表的浅复制,等于a[:]。 |
list = [1, 2, 1, 5]
print(list)
# [1, 2, 1, 5]
list.append(999)
print(list)
# [1, 2, 1, 5, 999]
list2 = [44, 55]
list.extend(list2)
print(list)
# [1, 2, 1, 5, 999, 44, 55]
list.insert(2, 'hhhh')
print(list)
# [1, 2, 'hhhh', 1, 5, 999, 44, 55]
list.remove('hhhh')
print(list)
# [1, 2, 1, 5, 999, 44, 55]
var = list2.pop(1)
print(var)
# 55
print(list2)
# [44]
list2.clear()
print(list2)
# []
print(list.index(2))
# 1
print(list.count(1))
# 2
list.sort()
print(list)
# [1, 1, 2, 5, 44, 55, 999]
list.reverse()
print(list)
# [999, 55, 44, 5, 2, 1, 1]
print(list.copy())
# [999, 55, 44, 5, 2, 1, 1]
'''
[1, 2, 1, 5]
[1, 2, 1, 5, 999]
[1, 2, 1, 5, 999, 44, 55]
[1, 2, 'hhhh', 1, 5, 999, 44, 55]
[1, 2, 1, 5, 999, 44, 55]
55
[44]
[]
1
2
[1, 1, 2, 5, 44, 55, 999]
[999, 55, 44, 5, 2, 1, 1]
[999, 55, 44, 5, 2, 1, 1]
'''
将列表当做堆栈使用
最先进入的元素最后一个被释放(后进先出)。用 append() 方法可以把一个元素添加到堆栈顶。用不指定索引的 pop() 方法可以把一个元素从堆栈顶释放出来。
stack = [1, 3, 'test', '999']
print(stack)
stack.append(33)
stack.append(44)
stack.append(55)
print(stack)
print(stack.pop())
print(stack.pop())
print(stack)
'''
[1, 3, 'test', '999']
[1, 3, 'test', '999', 33, 44, 55]
55
44
[1, 3, 'test', '999', 33]
'''
将列表当作队列使用
队列里第一加入的元素,第一个取出来
from collections import deque
queue = deque([1, 2, 'test', '999'])
queue.append('hhh')
queue.append('aaaa')
print(queue)
print(queue.popleft())
print(queue.popleft())
print(queue)
'''
[1, 3, 'test', '999', 33]
deque([1, 2, 'test', '999', 'hhh', 'aaaa'])
1
2
deque(['test', '999', 'hhh', 'aaaa'])
'''
列表推导式
列表推导式提供了从序列创建列表的简单途径。应用程序将一些操作应用于某个序列的每个元素,用其获得的结果作为生成新列表的元素,或者根据确定的判定条件创建子序列。
var = [1, 2, 4, 8]
print(var)
vvar = [2 * x for x in var]
print(vvar)
vvaar = [[x, 2 * x] for x in var]
print(vvaar)
var1 = [' dcc', ' ssss']
print([x.strip() for x in var1])
var2 = [2, 3, 4, 4]
var3 = [x * y for x in var for y in var2]
print(var3)
print([var[i] * var2[i] for i in range(len(var))])
print([str(round(355/113, i)) for i in range(1, 6)])
'''
[1, 2, 4, 8]
[2, 4, 8, 16]
[[1, 2], [2, 4], [4, 8], [8, 16]]
['dcc', 'ssss']
[2, 3, 4, 4, 4, 6, 8, 8, 8, 12, 16, 16, 16, 24, 32, 32]
[2, 6, 16, 32]
['3.1', '3.14', '3.142', '3.1416', '3.14159']
'''
嵌套列表解析
matrix = [
[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6]
]
print(matrix)
print([[row[i] for row in matrix] for i in range(4)])
# 3*4转为4*3
matrix = [
[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6]
]
transposed = []
for i in range(4):
transposed.append([row[i] for row in matrix])
print(transposed)
matrix = [
[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6]
]
transposed = []
for i in range(4):
# the following 3 lines implement the nested listcomp
transposed_row = []
for row in matrix:
transposed_row.append(row[i])
transposed.append(transposed_row)
print(transposed)
'''
[[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]
[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]
[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]
[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]
'''
del语句
使用 del 语句可以从一个列表中依索引而不是值来删除一个元素。
var = [1, 23, 3, 6, 'test']
print(var)
del var[2:3]
print(var)
del var[0:4:2]
print(var)
del var[:]
print(var)
del var
'''
[1, 23, 3, 6, 'test']
[1, 23, 6, 'test']
[23, 'test']
[]
'''
元组和序列
tuple = (1, 2, 3, 4, 5)
print(tuple)
tuple2 = tuple, ('test', 'hhhh', 'aaaa')
print(tuple2)
'''
(1, 2, 3, 4, 5)
((1, 2, 3, 4, 5), ('test', 'hhhh', 'aaaa'))
'''
集合
功能包括关系测试和消除重复元素
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket) # 删除重复的
# {'banana', 'orange', 'apple', 'pear'}
print('orange' in basket) # 检测成员
# True
print('crabgrass' in basket)
# False
# 以下演示了两个集合的操作
a = set('abracadabra')
b = set('alacazam')
print(a) # a 中唯一的字母
# {'c', 'r', 'b', 'a', 'd'}
print(a - b) # 在 a 中的字母,但不在 b 中
# {'r', 'b', 'd'}
print(a | b) # 在 a 或 b 中的字母
# {'c', 'r', 'l', 'm', 'z', 'b', 'a', 'd'}
print(a & b) # 在 a 和 b 中都有的字母
# {'c', 'a'}
print(a ^ b) # 在 a 或 b 中的字母,但不同时在 a 和 b 中
# {'m', 'z', 'r', 'b', 'l', 'd'}
a = {x for x in 'abracadabra' if x not in 'abc'}
print(a)
# {'d', 'r'}
'''
{'banana', 'orange', 'apple', 'pear'}
True
False
{'c', 'r', 'b', 'a', 'd'}
{'r', 'b', 'd'}
{'c', 'r', 'l', 'm', 'z', 'b', 'a', 'd'}
{'c', 'a'}
{'m', 'z', 'r', 'b', 'l', 'd'}
{'d', 'r'}
'''
字典
print(dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]))
# {'sape': 4139, 'guido': 4127, 'jack': 4098}
dict = {} # 空字典
print(dict)
# {}
dict[2] = 'test'
dict['test'] = 1
print(dict)
# {2: 'test', 'test': 1}
dict2 = {'test': 1, 1: 'dddd'}
print(dict2)
# {'test': 1, 1: 'dddd'}
print(dict[2], dict['test']) # 输出2,test的值
# test 1
print(dict2.keys()) # 输出所有键名
# dict_keys(['test', 1])
print(dict2.values()) # 输出所有键值
# dict_values([1, 'dddd'])
dict['test'] = 'txt' # 修改键值
print(dict)
# {2: 'test', 'test': 'txt'}
del dict2[1] # 删除一个键
print(dict2)
# {'test': 1}
dict2.clear() # 清空字典
print(dict2)
# {}
del dict2 # 删除字典
dict2 = {'1': 2, 'var': 'str', 'test': 'test', 'var': 'var'}
# 重复时后者覆盖前者
print(dict2)
# {'1': 2, 'var': 'var', 'test': 'test'}
'''
{'sape': 4139, 'guido': 4127, 'jack': 4098}
{}
{2: 'test', 'test': 1}
{'test': 1, 1: 'dddd'}
test 1
dict_keys(['test', 1])
dict_values([1, 'dddd'])
{2: 'test', 'test': 'txt'}
{'test': 1}
{}
{'1': 2, 'var': 'var', 'test': 'test'}
'''
如果关键字只是简单的字符串,使用关键字参数指定键值
dict(sape=4139, guido=4127, jack=4098)
#{'sape': 4139, 'jack': 4098, 'guido': 4127}
字典推导
dict3 = {x: x**2 for x in (2, 4, 6)}
print(dict3)
# {2: 4, 4: 16, 6: 36}
遍历技巧
# 关键字和对应的值可以使用 items() 方法同时解读
dict4 = {'123': 'test', '999': 'haha'}
print(dict4)
# {'123': 'test', '999': 'haha'}
for y, v in dict4.items():
print(y, v)
# 123 test
# 999 haha
# 索引位置和对应值可以使用 enumerate() 函数同时得到
list3 = ['111', 'test', '999']
print(list3)
# ['111', 'test', '999']
for i, v in enumerate(list3):
print(i, v)
'''
0 111
1 test
2 999
'''
# 同时遍历两个或更多的序列,可以使用 zip() 组合
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print('What is your {0}? It is {1}.'.format(q, a))
'''
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
'''
# 反向输出, 使用reversed()函数
for i in reversed(range(1, 10, 2)):
print(i, end=' ')
print()
# 9 7 5 3 1
# 顺序遍历一个序列,使用 sorted() 函数返回一个已排序的序列
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
for f in sorted(set(basket)):
print(f, end=' ')
print()
# apple banana orange pear
'''
{'123': 'test', '999': 'haha'}
123 test
999 haha
['111', 'test', '999']
0 111
1 test
2 999
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
9 7 5 3 1
apple banana orange pear
'''
模块
模块是一个包含所有你定义的函数和变量的文件,其后缀名是.py,意思是你能直接调用写好的函数或者变量来执行你的任务,这些写好的函数和变量被封装在一个文件包中
import sys
print('命令行参数如下:')
for i in sys.argv:
print(i)
print('\n\nPython 路径为:', sys.path, '\n')
- import sys 引入 python 标准库中的 sys.py 模块
- sys.argv 是一个包含命令行参数的列表
- sys.path 包含了一个 Python 解释器自动查找所需模块的路径的列表
import语句
import module1[, module2[,... moduleN]
- import只会导入一次
- 解释器收缩路径是在sys.path中确定
在sys.path任一路径下创建文件fibo.py
# 斐波那契(fibonacci)数列模块
def fib(n): # 定义到 n 的斐波那契数列
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
def fib2(n): # 返回到 n 的斐波那契数列
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
引入模块使用
fibo.fib(1000)
fibo.fib2(100)
fib = fibo.fib # 将函数赋给本地
from … import 语句
Python 的 from 语句让你从模块中导入一个指定的部分到当前命名空间中
from modname import name1[, name2[, ... nameN]]
要导入模块 fibo 的 fib 函数
from fibo import fib, fib2
这个声明不会把整个fibo模块导入到当前的命名空间中,它只会将fibo里的fib函数引入进来
from … import * 语句
把一个模块的所有内容全都导入到当前的命名空间
from modname import *
深入模式
模块除了方法定义,还可以包括可执行的代码。这些代码一般用来初始化这个模块。这些代码只有在第一次被导入时才会被执行。每个模块有各自独立的符号表,在模块内部为所有的函数当作全局符号表来使用。
导入模块的全局变量和本模块的全局变量是不影响的
__name__属性
- 用__name__属性来使该程序块仅在该模块自身运行时执行
- 每个模块都有一个__name__属性,当其值是’main‘时,表明该模块自身在运行,否则是被引入
- name 与 main 底下是双下划线, _ _ 是这样去掉中间的那个空格
if __name__ == '__main__':
print('程序自身在运行')
else:
print('我来自另一模块')
python using_name.py
程序自身在运行
>>> import using_name
我来自另一模块
dir()函数
内置的函数 dir() 可以找到模块内定义的所有名称。以一个字符串列表的形式返回
import sys
print(dir(sys))
'''
['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '__unraisablehook__', '_base_executable', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_enablelegacywindowsfsencoding', '_framework', '_getframe', '_git', '_home', '_xoptions', 'addaudithook', 'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix', 'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'getwindowsversion', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'pycache_prefix', 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'unraisablehook', 'version', 'version_info', 'warnoptions', 'winver']
'''
如果没有给定参数,那么 dir() 函数会罗列出当前定义的所有名称
import sys
print(dir())
'''
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'i', 'sys']
'''
标准模块
Python 本身带着一些标准的模块库,有些模块直接被构建在解析器里
import sys
print(sys.ps1)
print(sys.ps2)
包
包是一种管理 Python 模块命名空间的形式,采用”点模块名称”,比如一个模块的名称是 A.B, 那么他表示一个包 A中的子模块 B,例如
sound/ 顶层包
__init__.py 初始化 sound 包
formats/ 文件格式转换子包
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
effects/ 声音效果子包
__init__.py
echo.py
surround.py
reverse.py
...
filters/ filters 子包
__init__.py
equalizer.py
vocoder.py
karaoke.py
...
- 目录只有包含一个叫做 init.py 的文件才会被认作是一个包
- 使用形如 import item.subitem.subsubitem 这种导入形式,除了最后一项,都必须是包,而最后一项则可以是模块或者是包,但是不可以是类,函数或者变量的名字。
import sound.effects.echo
# 导入包里的特定模块
sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)
from sound.effects import echo
# 导入子模块的方法
echo.echofilter(input, output, delay=0.7, atten=4)
from sound.effects.echo import echofilter
# 直接导入一个函数或者变量
echofilter(input, output, delay=0.7, atten=4)
from package import item
#import 语法会首先把 item 当作一个包定义的名称,如果没找到,再试图按照一个模块去导入。如果还没找到,抛出一个 :exc:ImportError 异常。
从一个包中导入*
如果包定义文件 _init_.py 存在一个叫做 _all_ 的列表变量,那么在使用 from package import * 的时候就把这个列表中的所有名字作为包内容导入
__all__ = ["echo", "surround", "reverse"]如果 all 没有定义,那么使用**from sound.effects import ***这种语法的时候,就不会导入包 sound.effects 里的任何子模块
包还提供一个额外的属性__path__。这是一个目录列表,里面每一个包含的目录都有为这个包服务的__init__.py
输入输出
输入格式美化
print()write()sys.stdout标准输出文件str.format()多样化str()用户易读repr解释器易读
s = 'test'
print(str(s))
# test
print(repr(s))
# 'test'
print(str(1 / 7))
# 0.14285714285714285
print(repr(1 / 7))
# 0.14285714285714285
s = 'test\nhaha'
print(s)
'''
test
haha
'''
print(str(s))
'''
test
haha
'''
print(repr(s)) # repr将转义字符当做字符执行
# 'test\nhaha'
print(repr((s, [1, 2]))) # 注意括号
# ('test\nhaha', [1, 2])
# repr接收python所有类型
# 输出平方与立方表
for x in range(1, 11):
print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
# 注意前一行 'end' 的使用
print(repr(x*x*x).rjust(4))
# rjust() 方法, 它可以将字符串靠右, 并在左边填充空格
# zfill(), 它会在数字的左边填充 0
for x in range(1, 11):
print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
'''
test
'test'
0.14285714285714285
0.14285714285714285
test
haha
test
haha
'test\nhaha'
('test\nhaha', [1, 2])
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
'''
str.format()基本使用
# 常规输出
print('{}-{}'.format('one', 'two'))
# one-two
# 索引输入
print('{1}-{0}'.format('one', 'two'))
# two-one
# 关键字参数输出
print('{name}-{age}'.format(age='one', name='two'))
# two-one
# 结合
print('{1}-{0}-{test}'.format(1, 2, test='3'))
# 2-1-3
import math
# !a (使用 ascii()), !s (使用 str()) 和 !r (使用 repr())
print('{!a}'.format(math.pi))
# 3.141592653589793
# :后面.加数字代表保留几位小数,和类型
print('{0:.3f}。'.format(math.pi))
# 3.142。
# :后面加整数,表示证该域至少有这么多的宽度
table = {'Google': 1, 'Runoob': 2, 'Taobao': 3}
for name, number in table.items():
print('{0:10} ==> {1:10d}'.format(name, number))
'''
Google ==> 1
Runoob ==> 2
Taobao ==> 3
'''
# 传入一个字典, 然后使用方括号 [] 来访问键值
table = {'Google': 1, 'Runoob': 2, 'Taobao': 3}
print('Runoob: {0[Runoob]:d}; Google: {0[Google]:d}; Taobao: {0[Taobao]:d}'.format(table))
# Runoob: 2; Google: 1; Taobao: 3
# 通过在 table 变量前使用 ** 来实现相同的功能
table = {'Google': 1, 'Runoob': 2, 'Taobao': 3}
print('Runoob: {Runoob:d}; Google: {Google:d}; Taobao: {Taobao:d}'.format(**table))
# Runoob: 2; Google: 1; Taobao: 3
'''
one-two
two-one
two-one
2-1-3
3.141592653589793
3.142。
Google ==> 1
Runoob ==> 2
Taobao ==> 3
Runoob: 2; Google: 1; Taobao: 3
Runoob: 2; Google: 1; Taobao: 3
'''
旧式字符串格式化
print('%5.3f' % math.pi)
# 3.142
读取键盘输入
strstr = input("请输入:")
print("你输入的内容是: ", strstr)
print(type(strstr)) # 传入的值都为str
# 输入三角形的三边长
a, b, c = (input("请输入三角形三边的长:").split())
a = int(a)
b = int(b)
c = int(c)
# 计算三角形的半周长p
p = (a + b + c) / 2
# 计算三角形的面积s
s = (p * (p - a) * (p - b) * (p - c)) ** 0.5
# 输出三角形的面积
print("三角形面积为:", format(s, '.2f'))
'''
请输入:9
你输入的内容是: 9
<class 'str'>
请输入三角形三边的长:8 7 9
三角形面积为: 26.83
'''
读和写文件
open() 返回一个 file 对象
open(filename, mode)
- filename:包含了你要访问的文件名称的字符串值
- mode:决定了打开文件的模式:只读,写入,追加等,默认文件访问模式为只读(r)
| 模式 | 描述 |
|---|---|
| r | 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。 |
| rb | 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。 |
| r+ | 打开一个文件用于读写。文件指针将会放在文件的开头。 |
| rb+ | 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。 |
| w | 打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。 |
| wb | 以二进制格式打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。 |
| w+ | 打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。 |
| wb+ | 以二进制格式打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。 |
| a | 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。 |
| ab | 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。 |
| a+ | 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。 |
| ab+ | 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。 |
文件对象的方法
f.read()
f.read(size)将读取一定数目的数据, 然后作为字符串或字节对象返回,size 是一个可选的数字类型的参数,当 size 被忽略了或者为负, 那么该文件的所有内容都将被读取并且返回
# 打开一个文件
f = open("/tmp/foo.txt", "r")
str = f.read()
print(str)
# 关闭打开的文件
f.close()
f.readline()
f.readline() 会从文件中读取单独的一行,换行符为 ‘\n’,f.readline() 如果返回一个空字符串, 说明已经已经读取到最后一行
# 打开一个文件
f = open("/tmp/foo.txt", "r")
str = f.readline()
print(str)
# 关闭打开的文件
f.close()
f.readlines()
f.readlines() 将返回该文件中包含的所有行,如果设置可选参数 sizehint, 则读取指定长度的字节, 并且将这些字节按行分割
# 打开一个文件
f = open("/tmp/foo.txt", "r")
str = f.readlines()
print(str)
# 关闭打开的文件
f.close()
# 打开一个文件
f = open("/tmp/foo.txt", "r")
for line in f:
print(line, end='')
# 关闭打开的文件
f.close()
f.write()
f.write(string) 将 string 写入到文件中, 然后返回写入的字符数
不是字符串的需要先转换
# 打开一个文件
f = open("/tmp/foo.txt", "w")
num = f.write( "Python 是一个非常好的语言。\n是的,的确非常好!!\n" )
print(num)
# 关闭打开的文件
f.close()
# 29
f.tell()
f.tell() 返回文件对象当前所处的位置, 它是从文件开头开始算起的字节数
f.seek()
- f.seek(offset, from_what) 函数改变文件当前的位置
- from_what 的值, 如果是 0 表示开头, 如果是 1 表示当前位置, 2 表示文件的结尾
- from_what 值为默认为0,即文件开头
- seek(x,0) : 从起始位置即文件首行首字符开始移动 x 个字符
- seek(x,1) : 表示从当前位置往后移动x个字符
- seek(-x,2):表示从文件的结尾往前移动x个字符
f = open('/tmp/foo.txt', 'rb+')
f.write(b'0123456789abcdef')
# 16
f.seek(5) # 移动到文件的第六个字节
# 5
f.read(1)
# b'5'
f.seek(-3, 2) # 移动到文件的倒数第三字节
# 13
f.read(1)
# b'd'
f.close()
当你处理完一个文件后, 调用 f.close() 来关闭文件并释放系统的资源
pickle模块
python的pickle模块实现了基本的数据序列和反序列化
基本接口:
pickle.dump(obj, file, [,protocol])
有了 pickle 这个对象, 就能对 file 以读取的形式打开:
x = pickle.load(file)
示例
import pickle
# 使用pickle模块将数据对象保存到文件
data1 = {'a': [1, 2.0, 3, 4+6j],
'b': ('string', u'Unicode string'),
'c': None}
selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)
output = open('data.pkl', 'wb')
# Pickle dictionary using protocol 0.
pickle.dump(data1, output)
# Pickle the list using the highest protocol available.
pickle.dump(selfref_list, output, -1)
output.close()
File(文件)方法
open()方法
open() 函数常用形式
open(file, mode='r')
完整的语法格式
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
参数说明
- file: 必需,文件路径(相对或者绝对路径)
- mode: 可选,文件打开模式
- buffering: 设置缓冲
- encoding: 一般使用utf8
- errors: 报错级别
- newline: 区分换行符
- closefd: 传入的file参数类型
- opener: 设置自定义开启器,开启器的返回值必须是一个打开的文件描述符。
mode 参数
| 模式 | 描述 |
|---|---|
| t | 文本模式 (默认)。 |
| x | 写模式,新建一个文件,如果该文件已存在则会报错。 |
| b | 二进制模式。 |
| + | 打开一个文件进行更新(可读可写)。 |
| U | 通用换行模式(Python 3 不支持)。 |
| r | 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。 |
| rb | 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。一般用于非文本文件如图片等。 |
| r+ | 打开一个文件用于读写。文件指针将会放在文件的开头。 |
| rb+ | 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。一般用于非文本文件如图片等。 |
| w | 打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。 |
| wb | 以二进制格式打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。一般用于非文本文件如图片等。 |
| w+ | 打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。 |
| wb+ | 以二进制格式打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。一般用于非文本文件如图片等。 |
| a | 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。 |
| ab | 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。 |
| a+ | 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。 |
| ab+ | 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。 |
默认为文本模式,如果要以二进制模式打开,加上 b
file 对象
file 对象使用 open 函数来创建
file 对象常用的函数
| 序号 | 方法及描述 |
|---|---|
| 1 | file.close()关闭文件。关闭后文件不能再进行读写操作。 |
| 2 | file.flush()刷新文件内部缓冲,直接把内部缓冲区的数据立刻写入文件, 而不是被动的等待输出缓冲区写入。 |
| 3 | file.fileno()返回一个整型的文件描述符(file descriptor FD 整型), 可以用在如os模块的read方法等一些底层操作上。 |
| 4 | file.isatty()如果文件连接到一个终端设备返回 True,否则返回 False。 |
| 5 | file.next()Python 3 中的 File 对象不支持 next() 方法。返回文件下一行。 |
| 6 | [file.read(size])从文件读取指定的字节数,如果未给定或为负则读取所有。 |
| 7 | [file.readline(size])读取整行,包括 “\n” 字符。 |
| 8 | [file.readlines(sizeint])读取所有行并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行, 实际读取值可能比 sizeint 较大, 因为需要填充缓冲区。 |
| 9 | [file.seek(offset, whence])移动文件读取指针到指定位置 |
| 10 | file.tell()返回文件当前位置。 |
| 11 | [file.truncate(size])从文件的首行首字符开始截断,截断文件为 size 个字符,无 size 表示从当前位置截断;截断之后后面的所有字符被删除,其中 windows 系统下的换行代表2个字符大小。 |
| 12 | file.write(str)将字符串写入文件,返回的是写入的字符长度。 |
| 13 | file.writelines(sequence)向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符。 |
OS 文件/目录方法
一部分函数只能在linux中使用
| 序号 | 方法及描述 |
|---|---|
| 1 | os.access(path, mode) 检验权限模式 |
| 2 | os.chdir(path) 改变当前工作目录 |
| 3 | os.chflags(path, flags) 设置路径的标记为数字标记。 |
| 4 | os.chmod(path, mode) 更改权限 |
| 5 | os.chown(path, uid, gid) 更改文件所有者 |
| 6 | os.chroot(path) 改变当前进程的根目录 |
| 7 | os.close(fd) 关闭文件描述符 fd |
| 8 | os.closerange(fd_low, fd_high) 关闭所有文件描述符,从 fd_low (包含) 到 fd_high (不包含), 错误会忽略 |
| 9 | os.dup(fd) 复制文件描述符 fd |
| 10 | os.dup2(fd, fd2) 将一个文件描述符 fd 复制到另一个 fd2 |
| 11 | os.fchdir(fd) 通过文件描述符改变当前工作目录 |
| 12 | os.fchmod(fd, mode) 改变一个文件的访问权限,该文件由参数fd指定,参数mode是Unix下的文件访问权限。 |
| 13 | os.fchown(fd, uid, gid) 修改一个文件的所有权,这个函数修改一个文件的用户ID和用户组ID,该文件由文件描述符fd指定。 |
| 14 | os.fdatasync(fd) 强制将文件写入磁盘,该文件由文件描述符fd指定,但是不强制更新文件的状态信息。 |
| 15 | [os.fdopen(fd, mode[, bufsize]]) 通过文件描述符 fd 创建一个文件对象,并返回这个文件对象 |
| 16 | os.fpathconf(fd, name) 返回一个打开的文件的系统配置信息。name为检索的系统配置的值,它也许是一个定义系统值的字符串,这些名字在很多标准中指定(POSIX.1, Unix 95, Unix 98, 和其它)。 |
| 17 | os.fstat(fd) 返回文件描述符fd的状态,像stat()。 |
| 18 | os.fstatvfs(fd) 返回包含文件描述符fd的文件的文件系统的信息,Python 3.3 相等于 statvfs()。 |
| 19 | os.fsync(fd) 强制将文件描述符为fd的文件写入硬盘。 |
| 20 | os.ftruncate(fd, length) 裁剪文件描述符fd对应的文件, 所以它最大不能超过文件大小。 |
| 21 | os.getcwd() 返回当前工作目录 |
| 22 | os.getcwdb() 返回一个当前工作目录的Unicode对象 |
| 23 | os.isatty(fd) 如果文件描述符fd是打开的,同时与tty(-like)设备相连,则返回true, 否则False。 |
| 24 | os.lchflags(path, flags) 设置路径的标记为数字标记,类似 chflags(),但是没有软链接 |
| 25 | os.lchmod(path, mode) 修改连接文件权限 |
| 26 | os.lchown(path, uid, gid) 更改文件所有者,类似 chown,但是不追踪链接。 |
| 27 | os.link(src, dst) 创建硬链接,名为参数 dst,指向参数 src |
| 28 | os.listdir(path) 返回path指定的文件夹包含的文件或文件夹的名字的列表。 |
| 29 | os.lseek(fd, pos, how) 设置文件描述符 fd当前位置为pos, how方式修改: SEEK_SET 或者 0 设置从文件开始的计算的pos; SEEK_CUR或者 1 则从当前位置计算; os.SEEK_END或者2则从文件尾部开始. 在unix,Windows中有效 |
| 30 | os.lstat(path) 像stat(),但是没有软链接 |
| 31 | os.major(device) 从原始的设备号中提取设备major号码 (使用stat中的st_dev或者st_rdev field)。 |
| 32 | os.makedev(major, minor) 以major和minor设备号组成一个原始设备号 |
| 33 | [os.makedirs(path, mode]) 递归文件夹创建函数。像mkdir(), 但创建的所有intermediate-level文件夹需要包含子文件夹。 |
| 34 | os.minor(device) 从原始的设备号中提取设备minor号码 (使用stat中的st_dev或者st_rdev field )。 |
| 35 | [os.mkdir(path, mode]) 以数字mode的mode创建一个名为path的文件夹.默认的 mode 是 0777 (八进制)。 |
| 36 | [os.mkfifo(path, mode]) 创建命名管道,mode 为数字,默认为 0666 (八进制) |
| 37 | [os.mknod(filename, mode=0600, device]) 创建一个名为filename文件系统节点(文件,设备特别文件或者命名pipe)。 |
| 38 | [os.open(file, flags, mode]) 打开一个文件,并且设置需要的打开选项,mode参数是可选的 |
| 39 | os.openpty() 打开一个新的伪终端对。返回 pty 和 tty的文件描述符。 |
| 40 | os.pathconf(path, name) 返回相关文件的系统配置信息。 |
| 41 | os.pipe() 创建一个管道. 返回一对文件描述符(r, w) 分别为读和写 |
| 42 | [os.popen(command, mode[, bufsize]]) 从一个 command 打开一个管道 |
| 43 | os.read(fd, n) 从文件描述符 fd 中读取最多 n 个字节,返回包含读取字节的字符串,文件描述符 fd对应文件已达到结尾, 返回一个空字符串。 |
| 44 | os.readlink(path) 返回软链接所指向的文件 |
| 45 | os.remove(path) 删除路径为path的文件。如果path 是一个文件夹,将抛出OSError; 查看下面的rmdir()删除一个 directory。 |
| 46 | os.removedirs(path) 递归删除目录。 |
| 47 | os.rename(src, dst) 重命名文件或目录,从 src 到 dst |
| 48 | os.renames(old, new) 递归地对目录进行更名,也可以对文件进行更名。 |
| 49 | os.rmdir(path) 删除path指定的空目录,如果目录非空,则抛出一个OSError异常。 |
| 50 | os.stat(path) 获取path指定的路径的信息,功能等同于C API中的stat()系统调用。 |
| 51 | [os.stat_float_times(newvalue]) 决定stat_result是否以float对象显示时间戳 |
| 52 | os.statvfs(path) 获取指定路径的文件系统统计信息 |
| 53 | os.symlink(src, dst) 创建一个软链接 |
| 54 | os.tcgetpgrp(fd) 返回与终端fd(一个由os.open()返回的打开的文件描述符)关联的进程组 |
| 55 | os.tcsetpgrp(fd, pg) 设置与终端fd(一个由os.open()返回的打开的文件描述符)关联的进程组为pg。 |
| 56 | os.tempnam([dir[, prefix]]) Python3 中已删除。返回唯一的路径名用于创建临时文件。 |
| 57 | os.tmpfile() Python3 中已删除。返回一个打开的模式为(w+b)的文件对象 .这文件对象没有文件夹入口,没有文件描述符,将会自动删除。 |
| 58 | os.tmpnam() Python3 中已删除。为创建一个临时文件返回一个唯一的路径 |
| 59 | os.ttyname(fd) 返回一个字符串,它表示与文件描述符fd 关联的终端设备。如果fd 没有与终端设备关联,则引发一个异常。 |
| 60 | os.unlink(path) 删除文件路径 |
| 61 | os.utime(path, times) 返回指定的path文件的访问和修改的时间。 |
| 62 | [os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])](https://www.runoob.com/python3/python3-os-walk.html) 输出在文件夹中的文件名通过在树中游走,向上或者向下。 |
| 63 | os.write(fd, str) 写入字符串到文件描述符 fd中. 返回实际写入的字符串长度 |
| 64 | os.path 模块 获取文件的属性信息。 |
| 65 | os.pardir() 获取当前目录的父目录,以字符串形式显示目录名。 |
import os
import stat
ret = os.access("D:/test.txt", os.F_OK)
print("F_OK - 返回值 %s" % ret)
# F_OK - 返回值 True
ret = os.access("D:/test.txt", os.R_OK)
print("R_OK - 返回值 %s" % ret)
# R_OK - 返回值 True
ret = os.access("D:/test.txt", os.W_OK)
print("W_OK - 返回值 %s" % ret)
# W_OK - 返回值 True
ret = os.access("D:/test.txt", os.X_OK)
print("X_OK - 返回值 %s" % ret)
# X_OK - 返回值 True
path = 'D:/'
# 查看当前工作目录
retval = os.getcwd()
print("当前工作目录为 %s" % retval)
print("当前工作目录 : %s" % os.getcwdb())
# 当前工作目录为 F:\
# 修改当前工作目录
os.chdir(path)
# 查看修改后的工作目录
retval = os.getcwd()
print("目录修改成功 %s" % retval)
# 目录修改成功 D:\
# path = '/tmp/foo.txt'
# # 为文件设置标记,使得它不能被重命名和删除
# flags = stat.SF_NOUNLINK
# retval = os.chflags(path, flags)
# print("返回值: %s" % retval)
path = 'D:/test.txt'
import os, sys, stat
# 设置文件可以通过用户组执行
os.chmod("D:/test.txt", stat.S_IXGRP)
# 设置文件可以被其他用户写入
os.chmod("D:/test.txt", stat.S_IWOTH)
print("修改成功!!")
# 设置所有者 ID 为 100
# os.chown("/tmp/foo.txt", 100, -1)
# print("修改权限成功!!")
# 设置根目录为 /tmp
# os.chroot("/tmp")
# print("修改根目录成功!!")
# 打开文件
# fd = os.open("foo.txt", os.O_RDWR | os.O_CREAT)
# # 写入字符串
# os.write(fd, "This is test")
# d_fd = os.dup( fd )
# # 关闭文件
# os.close(fd)
# print("关闭文件成功!!")
# 创建的目录
# path = "/tmp/home/monthly/daily/hourly"
#
# os.mkdir(path, 0o755)
#
# print("目录已创建")
# 创建的目录
# path = "/tmp/hourly"
#
# os.mkfifo(path, 0o644)
#
# print("路径被创建")
# # 列出目录
# print("目录为: %s" % os.listdir(os.getcwd()))
#
# # 移除
# os.remove("aa.txt")
#
# # 移除后列出目录
# print("移除后 : %s" % os.listdir(os.getcwd()))
# os.renames(old, new)
# # 列出目录
# print("目录为: %s"%os.listdir(os.getcwd()))
#
# # 删除路径
# os.rmdir("mydir")
#
# # 列出重命名后的目录
# print("目录为: %s" %os.listdir(os.getcwd())
# # 显示文件 "a2.py" 信息
# statinfo = os.stat('a2.py')
#
# print(statinfo)
# # 打开文件
# fd = os.open("f1.txt", os.O_RDWR | os.O_CREAT)
#
# # 写入字符串
# str = "This is runoob.com site"
# ret = os.write(fd, bytes(str, 'UTF-8'))
#
# # 输入返回值
# print("写入的位数为: ")
# print(ret)
#
# print("写入成功")
#
# # 关闭文件
# os.close(fd)
# print("关闭文件成功!!")
错误和异常
语法错误
一般为漏写符号,或者拼写错误报错
语法分析器指出了出错的一行,并且在最先找到的错误的位置标记一个小小的箭头
异常
即便 Python 程序的语法是正确的,在运行它的时候,也有可能发生错误。运行期检测到的错误被称为异常
print(10 / 0) # 除数不能为0报异常
print(2 +'2') # 类型不能相加,触发异常
python标准异常
| 异常名称 | 描述 |
|---|---|
| BaseException | 所有异常的基类 |
| SystemExit | 解释器请求退出 |
| KeyboardInterrupt | 用户中断执行(通常是输入^C) |
| Exception | 常规错误的基类 |
| StopIteration | 迭代器没有更多的值 |
| GeneratorExit | 生成器(generator)发生异常来通知退出 |
| StandardError | 所有的内建标准异常的基类 |
| ArithmeticError | 所有数值计算错误的基类 |
| FloatingPointError | 浮点计算错误 |
| OverflowError | 数值运算超出最大限制 |
| ZeroDivisionError | 除(或取模)零 (所有数据类型) |
| AssertionError | 断言语句失败 |
| AttributeError | 对象没有这个属性 |
| EOFError | 没有内建输入,到达EOF 标记 |
| EnvironmentError | 操作系统错误的基类 |
| IOError | 输入/输出操作失败 |
| OSError | 操作系统错误 |
| WindowsError | 系统调用失败 |
| ImportError | 导入模块/对象失败 |
| LookupError | 无效数据查询的基类 |
| IndexError | 序列中没有此索引(index) |
| KeyError | 映射中没有这个键 |
| MemoryError | 内存溢出错误(对于Python 解释器不是致命的) |
| NameError | 未声明/初始化对象 (没有属性) |
| UnboundLocalError | 访问未初始化的本地变量 |
| ReferenceError | 弱引用(Weak reference)试图访问已经垃圾回收了的对象 |
| RuntimeError | 一般的运行时错误 |
| NotImplementedError | 尚未实现的方法 |
| SyntaxError | Python 语法错误 |
| IndentationError | 缩进错误 |
| TabError | Tab 和空格混用 |
| SystemError | 一般的解释器系统错误 |
| TypeError | 对类型无效的操作 |
| ValueError | 传入无效的参数 |
| UnicodeError | Unicode 相关的错误 |
| UnicodeDecodeError | Unicode 解码时的错误 |
| UnicodeEncodeError | Unicode 编码时错误 |
| UnicodeTranslateError | Unicode 转换时错误 |
| Warning | 警告的基类 |
| DeprecationWarning | 关于被弃用的特征的警告 |
| FutureWarning | 关于构造将来语义会有改变的警告 |
| OverflowWarning | 旧的关于自动提升为长整型(long)的警告 |
| PendingDeprecationWarning | 关于特性将会被废弃的警告 |
| RuntimeWarning | 可疑的运行时行为(runtime behavior)的警告 |
| SyntaxWarning | 可疑的语法的警告 |
| UserWarning | 用户代码生成的警告 |
异常处理
try/except
基本格式
try:
执行代码
except:
异常时执行的代码
while True:
try:
x = int(input("请输入一个数字: "))
break
except ValueError:
print("您输入的不是数字,请再次尝试输入!")
'''
请输入一个数字: qq
您输入的不是数字,请再次尝试输入!
'''
- 首先执行try字句
- 没有异常忽略except,结束try
- 如果有异常,忽略try语句发生异常后面的语句,执行与except中与try发生的异常相符的语句
- 如果没有相符的,那么这个异常将会传递给上层的 try 中
一个except语句同时处理多个异常,这些异常将被放在一个括号里成为一个元组
except (RuntimeError, TypeError, NameError):
pass
一个 try 语句可能包含多个except子句,分别来处理不同的特定的异常。最多只有一个分支会被执行。
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
try/except…else
基本格式
try:
执行代码
except:
异常时执行的代码
else:
没有异常执行的代码
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')
f.close()
try-finally 语句
基本格式
try:
执行代码
except:
异常时执行的代码
else:
没有异常执行的代码
finally:
无论如何都要执行的代码
try:
runoob()
except AssertionError as error:
print(error)
else:
try:
with open('file.log') as file:
read_data = file.read()
except FileNotFoundError as fnf_error:
print(fnf_error)
finally:
print('这句话,无论异常是否发生都会执行。')
'''
这句话,无论异常是否发生都会执行。
Traceback (most recent call last):
File xxxx in <module>
runoob()
NameError: name 'runoob' is not defined
'''
抛出异常
使用 raise 语句抛出一个指定的异常
raise [Exception [, args [, traceback]]]
x = 10
if x > 5:
raise Exception('x 不能大于 5。x 的值为: {}'.format(x))
'''
Traceback (most recent call last):
File xxx in <module>
raise Exception('x 不能大于 5。x 的值为: {}'.format(x))
Exception: x 不能大于 5。x 的值为: 10
'''
try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
raise
'''
Traceback (most recent call last):
File xxxx in <module>
raise NameError('HiThere')
NameError: HiThere
'''
用户自定义异常
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
try:
raise MyError(2 * 2)
except MyError as e:
print('My exception occurred, value:', e.value)
raise MyError('oops!')
'''
Traceback (most recent call last):
File xxx in <module>
raise MyError('oops!')
__main__.MyError: 'oops!'
My exception occurred, value: 4
'''
定义清理行为
不管 try 子句里面有没有发生异常,finally 子句都会执行
try:
raise KeyboardInterrupt
finally:
print('Goodbye, world!')
'''
Traceback (most recent call last):
File xxx in <module>
raise KeyboardInterrupt
KeyboardInterrupt
Goodbye, world!
'''
预定义的清理行为
一些对象定义了标准的清理行为,无论系统是否成功的使用了它,一旦不需要它了,那么这个标准的清理行为就会执行
for line in open("myfile.txt"):
print(line, end="")
以上这段代码的问题是,当执行完毕后,文件会保持打开状态,并没有被关闭
关键词 with 语句就可以保证诸如文件之类的对象在使用完之后一定会正确的执行他的清理方法
with open("myfile.txt") as f:
for line in f:
print(line, end="")
以上这段代码执行完毕后,就算在处理过程中出问题了,文件 f 总是会关闭
面向对象
简介
- 类(Class): 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。
- 方法:类中定义的函数。
- 类变量:类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。
- 数据成员:类变量或者实例变量用于处理类及其实例对象的相关的数据。
- 方法重写:如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。
- 局部变量:定义在方法中的变量,只作用于当前实例的类。
- 实例变量:在类的声明中,属性是用变量来表示的,这种变量就称为实例变量,实例变量就是一个用 self 修饰的变量。
- 继承:即一个派生类(derived class)继承基类(base class)的字段和方法。继承也允许把一个派生类的对象作为一个基类对象对待。
- 实例化:创建一个类的实例,类的具体对象。
- 对象:通过类定义的数据结构实例。对象包括两个数据成员(类变量和实例变量)和方法。
类定义
class ClassName:
<statement-1>
.
.
.
<statement-N>
类对象
- 类对象支持属性引用和实例化
- 属性引用格式 obj.name
- 类对象创建后,类命名空间中所有的命名都是有效属性名
- 类有一个名为 _init_() 的特殊方法(构造方法),该方法在类实例化时会自动调用
class MyClass:
"""一个简单的类实例"""
i = 12345
def f(self):
return 'hello world'
# 实例化类
x = MyClass()
# 访问类的属性和方法
print("MyClass 类的属性 i 为:", x.i)
print("MyClass 类的方法 f 输出为:", x.f())
'''
MyClass 类的属性 i 为: 12345
MyClass 类的方法 f 输出为: hello world
'''
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
x = Complex(3.0, -4.5)
print(x.r, x.i) # 输出结果:3.0 -4.5
self代表类的实例,而非类
class Test:
def prt(self):
print(self)
print(self.__class__)
t = Test()
t.prt()
'''
<__main__.Test object at 0x000001A9BBFF6A60>
<class '__main__.Test'>
'''
self不是关键字,换成其他的也行
类的方法
- 使用def关键字来定义一个方法
- 必须包含参数self并且为第一个
#类定义
class people:
#定义基本属性
name = ''
age = 0
#定义私有属性,私有属性在类外部无法直接进行访问
__weight = 0
#定义构造方法
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s 说: 我 %d 岁。" %(self.name,self.age))
# 实例化类
p = people('runoob',10,30)
p.speak()
'''
runoob 说: 我 10 岁。
'''
继承
子类(派生类 DerivedClassName)会继承父类(基类 BaseClassName)的属性和方法
class DerivedClassName(BaseClassName):
<statement-1>
.
.
.
<statement-N>
基类定义在另一个模块中时
class DerivedClassName(modname.BaseClassName):
#类定义
class people:
#定义基本属性
name = ''
age = 0
#定义私有属性,私有属性在类外部无法直接进行访问
__weight = 0
#定义构造方法
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s 说: 我 %d 岁。" %(self.name,self.age))
#单继承示例
class student(people):
grade = ''
def __init__(self,n,a,w,g):
#调用父类的构函
people.__init__(self,n,a,w)
self.grade = g
#覆写父类的方法
def speak(self):
print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
s = student('ken',10,60,3)
s.speak()
'''
ken 说: 我 10 岁了,我在读 3 年级
'''
- 继承时可以直接调用父类构造函数,再添加新的变量
- 父类的方法也能直接调用或者重写
- 子类不重写 **_init**,实例化子类时,会自动调用父类定义的 **_init**
多继承
class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
.
.
<statement-N>
若是父类中有相同的方法名,而在子类使用时未指定,python从左至右搜索 即方法在子类中未找到时,从左到右查找父类中是否包含方法
#类定义
class people:
#定义基本属性
name = ''
age = 0
#定义私有属性,私有属性在类外部无法直接进行访问
__weight = 0
#定义构造方法
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s 说: 我 %d 岁。" %(self.name,self.age))
#单继承示例
class student(people):
grade = ''
def __init__(self,n,a,w,g):
#调用父类的构函
people.__init__(self,n,a,w)
self.grade = g
#覆写父类的方法
def speak(self):
print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
#另一个类,多重继承之前的准备
class speaker():
topic = ''
name = ''
def __init__(self,n,t):
self.name = n
self.topic = t
def speak(self):
print("我叫 %s,我是一个演说家,我演讲的主题是 %s"%(self.name,self.topic))
#多重继承
class sample(speaker,student):
a =''
def __init__(self,n,a,w,g,t):
student.__init__(self,n,a,w,g)
speaker.__init__(self,n,t)
test = sample("Tim",25,80,4,"Python")
test.speak() #方法名同,默认调用的是在括号中排前地父类的方法
'''
我叫 Tim,我是一个演说家,我演讲的主题是 Python
'''
方法重写
super() 函数是用于调用父类(超类)的一个方法
class Parent: # 定义父类
def myMethod(self):
print ('调用父类方法')
class Child(Parent): # 定义子类
def myMethod(self):
print ('调用子类方法')
c = Child() # 子类实例
c.myMethod() # 子类调用重写方法
super(Child,c).myMethod() #用子类对象调用父类已被覆盖的方法
'''
调用子类方法
调用父类方法
'''
子类继承父类构造函数说明
子类不重写 **_init**,实例化子类时,会自动调用父类定义的 **_init**
class Father(object):
def __init__(self, name):
self.name=name
print ( "name: %s" %( self.name) )
def getName(self):
return 'Father ' + self.name
class Son(Father):
def getName(self):
return 'Son '+self.name
if __name__=='__main__':
son=Son('runoob')
print ( son.getName() )
'''
name: runoob
Son runoob
'''
如果重写了_init_ 时,实例化子类,就不会调用父类已经定义的 _init_
如果重写了_init_ 时,要继承父类的构造方法,可以使用 super 关键字
super(子类,self).__init__(参数1,参数2,....)
还有一种经典写法
父类名称.__init__(self,参数1,参数2,...)
class Father(object):
def __init__(self, name):
self.name=name
print ( "name: %s" %( self.name))
def getName(self):
return 'Father ' + self.name
class Son(Father):
def __init__(self, name):
super(Son, self).__init__(name)
print ("hi")
self.name = name
def getName(self):
return 'Son '+self.name
if __name__=='__main__':
son=Son('runoob')
print ( son.getName() )
'''
name: runoob
hi
Son runoob
'''
类属性与方法
类的私有属性
__private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs
class JustCounter:
__secretCount = 0 # 私有变量
publicCount = 0 # 公开变量
def count(self):
self.__secretCount += 1
self.publicCount += 1
print (self.__secretCount)
counter = JustCounter()
counter.count()
counter.count()
print (counter.publicCount)
print (counter.__secretCount) # 报错,实例不能访问私有变量
'''
1
2
2
Traceback (most recent call last):
File "test.py", line 16, in <module>
print (counter.__secretCount) # 报错,实例不能访问私有变量
AttributeError: 'JustCounter' object has no attribute '__secretCount'
'''
类的方法
在类的内部,使用 def 关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self,且为第一个参数,self 代表的是类的实例
self 的名字并不是规定死的,也可以使用 this,但是最好还是按照约定使用 self
类的私有方法
__private_method:两个下划线开头,声明该方法为私有方法,只能在类的内部调用 ,不能在类的外部调用self.__private_methods
class Site:
def __init__(self, name, url):
self.name = name # public
self.__url = url # private
def who(self):
print('name : ', self.name)
print('url : ', self.__url)
def __foo(self): # 私有方法
print('这是私有方法')
def foo(self): # 公共方法
print('这是公共方法')
self.__foo()
x = Site('菜鸟教程', 'www.runoob.com')
x.who() # 正常输出
x.foo() # 正常输出
x.__foo() # 报错
'''
name : 菜鸟教程
url : www.runoob.com
这是公共方法
这是私有方法
Traceback (most recent call last):
File xxxx in <module>
x.__foo() # 报错
AttributeError: 'Site' object has no attribute '__foo'
'''
类的专有方法
- init : 构造函数,在生成对象时调用
- del : 析构函数,释放对象时使用
- repr : 打印,转换
- setitem : 按照索引赋值
- getitem: 按照索引获取值
- len: 获得长度
- cmp: 比较运算
- call: 函数调用
- add: 加运算
- sub: 减运算
- mul: 乘运算
- truediv: 除运算
- mod: 求余运算
- pow: 乘方
运算符重载
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)
# Vector(7,8)
命名空间和作用域
命名空间
- 命名空间(Namespace)是从名称到对象的映射,大部分的命名空间都是通过 Python 字典来实现的
- 各个命名空间是独立的,所以一个命名空间中不能有重名,不同的命名空间可以重名
- 命名空间的生命周期取决于对象的作用域,如果对象执行完成,则该命名空间的生命周期就结束
- 无法从外部命名空间访问内部命名空间的对象
三种命名空间
- 内置名称(built-in names), Python 语言内置的名称,比如函数名 abs、char 和异常名称 BaseException、Exception 等等
- 全局名称(global names),模块中定义的名称,记录了模块的变量,包括函数、类、其它导入的模块、模块级的变量和常量
- 局部名称(local names),函数中定义的名称,记录了函数的变量,包括函数的参数和局部定义的变量。(类中定义的也是)
查找顺序为:局部的命名空间去 -> 全局命名空间 -> 内置命名空间
如果找不到变量,它将放弃查找并引发一个 NameError 异常
# var1 是全局名称
var1 = 5
def some_func():
# var2 是局部名称
var2 = 6
def some_inner_func():
# var3 是内嵌的局部名称
var3 = 7
作用域
- 作用域就是一个 Python 程序可以直接访问命名空间的正文区域
- 程序的变量并不是在哪个位置都可以访问的,访问权限决定于这个变量是在哪里赋值的
四种作用域
- L(Local):最内层,包含局部变量,比如一个函数/方法内部
- E(Enclosing):包含了非局部(non-local)也非全局(non-global)的变量。比如两个嵌套函数,一个函数(或类) A 里面又包含了一个函数 B ,那么对于 B 中的名称来说 A 中的作用域就为 nonlocal
- G(Global):当前脚本的最外层,比如当前模块的全局变量。
- B(Built-in): 包含了内建的变量/关键字等,最后被搜索。
规则顺序: L –> E –> G –> B
g_count = 0 # 全局作用域
def outer():
o_count = 1 # 闭包函数外的函数中
def inner():
i_count = 2 # 局部作用域
内置作用域通过一个名为 builtin 的标准模块来实现
import builtins
print(dir(builtins)) # 输出预定义变量
Python 中只有模块(module),类(class)以及函数(def、lambda)才会引入新的作用域,其它的代码块(如 if/elif/else/、try/except、for/while等)是不会引入新的作用域的,也就是说这些语句内定义的变量,外部也可以访问
if True:
msg = 'I am from Runoob' # 外部可以访问
def test():
msg_inner = 'I am from Runoob' # 外部不能访问
全局变量和局部变量
- 定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域
- 局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问
- 调用函数时,所有在函数内声明的变量名称都将被加入到作用域中
total = 0 # 这是一个全局变量
# 可写函数说明
def sum( arg1, arg2 ):
#返回2个参数的和."
total = arg1 + arg2 # total在这里是局部变量.
print ("函数内是局部变量 : ", total)
return total
#调用sum函数
sum( 10, 20 )
print ("函数外是全局变量 : ", total)
'''
函数内是局部变量 : 30
函数外是全局变量 : 0
'''
global 和 nonlocal关键字
当内部作用域想修改外部作用域的变量时,用到 global 和 nonlocal 关键字
# 修改全局变量 num
num = 1
def fun1():
global num # 需要使用 global 关键字声明
print(num)
num = 123
print(num)
fun1()
print(num)
'''
1
123
123
'''
nonlocal 修改嵌套作用域(enclosing 作用域,外层非全局作用域)中的变量
def outer():
num = 10
def inner():
nonlocal num # nonlocal关键字声明
num = 100
print(num)
inner()
print(num)
outer()
'''
100
100
'''
标准库概览
操作系统接口
os模块提供了不少与操作系统相关联的函数
import os
print(os.getcwd()) # 返回当前的工作目录
os.chdir('/server/accesslogs') # 修改当前的工作目录
os.system('mkdir today') # 执行系统命令 mkdir
print(dir(os)) # returns a list of all module functions
print(help(os)) # 帮助文档
针对日常的文件和目录管理任务,:mod:shutil 模块提供了一个易于使用的高级接口
import shutil
shutil.copyfile('data.db', 'archive.db')
shutil.move('/build/executables', 'installdir')
文件通配符
glob模块提供了一个函数用于从目录通配符搜索中生成文件列表
import glob
print(glob.glob('*.py'))
# ['xxx.py', 'xxx.py', 'xxx.py']
命令行参数
通用工具脚本经常调用命令行参数。这些命令行参数以链表形式存储于 sys 模块的 argv 变量。例如在命令行中执行 “python demo.py one two three” 后可以得到以下输出结果:
import sys
print(sys.argv)
错误输出重定向和程序终止
sys 还有 stdin,stdout 和 stderr 属性,即使在 stdout 被重定向时,后者也可以用于显示警告和错误信息
sys.stderr.write('Warning, log file not found starting a new one\n')
大多脚本的定向终止都使用 sys.exit()
字符串正则匹配
re模块为高级字符串处理提供了正则表达式工具
import re
print(re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest'))
# ['foot', 'fell', 'fastest']
print(re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat'))
# 'cat in the hat'
数学
math模块为浮点运算提供了对底层C函数库的访问
import math
print(math.cos(math.pi / 4))
# 0.70710678118654757
print(math.log(1024, 2))
# 10.0
random提供了生成随机数的工具
import random
print(random.choice(['apple', 'pear', 'banana']))
# 'apple'
print(random.sample(range(100), 10)) # sampling without replacement
# [30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
print(random.random()) # random float
# 0.17970987693706186
print(random.randrange(6)) # random integer chosen from range(6)
# 3
访问互联网
有几个模块用于访问互联网以及处理网络通信协议,处理从 urls 接收的数据的 urllib.request 以及用于发送电子邮件的 smtplib
from urllib.request import urlopen
for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
line = line.decode('utf-8') # Decoding the binary data to text.
if 'EST' in line or 'EDT' in line: # look for Eastern Time
print(line)
# <BR>Nov. 25, 09:43:32 PM EST
import smtplib
server = smtplib.SMTP('localhost')
server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
"""To: jcaesar@example.org
From: soothsayer@example.org
Beware the Ides of March.
""")
server.quit()
日期和时间
datetime模块为日期和时间处理
该模块还支持时区处理
# dates are easily constructed and formatted
from datetime import date
now = date.today()
print(now)
# 2021-09-26
print(now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B."))
# 09-26-21. 26 Sep 2021 is a Sunday on the 26 day of September.
# dates support calendar arithmetic
birthday = date(1964, 7, 31)
age = now - birthday
print(age.days)
# 20876
数据压缩
以下模块直接支持通用的数据打包和压缩格式:zlib,gzip,bz2,zipfile,以及 tarfile
import zlib
s = b'witch which has which witches wrist watch'
print(len(s))
# 41
t = zlib.compress(s)
print(len(t))
# 37
print(zlib.decompress(t))
# b'witch which has which witches wrist watch'
print(zlib.crc32(s))
# 226805979
性能度量
from timeit import Timer
print(Timer('t=a; a=b; b=t', 'a=1; b=2').timeit())
# 0.032305799999999996
print(Timer('a,b = b,a', 'a=1; b=2').timeit())
# 0.025154800000000005
测试模块
doctest模块提供了一个工具,扫描模块并根据程序中内嵌的文档字符串执行测试
def average(values):
"""Computes the arithmetic mean of a list of numbers.
>>> print(average([20, 30, 70]))
40.0
"""
return sum(values) / len(values)
import doctest
doctest.testmod() # 自动验证嵌入测试
unittest模块不像 doctest模块那么容易使用,不过它可以在一个独立的文件里提供一个更全面的测试集
import unittest
class TestStatisticalFunctions(unittest.TestCase):
def test_average(self):
self.assertEqual(average([20, 30, 70]), 40.0)
self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
self.assertRaises(ZeroDivisionError, average, [])
self.assertRaises(TypeError, average, 20, 30, 70)
unittest.main() # Calling from the command line invokes all tests
时间和日期
- 每个时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示
- 时间间隔是以秒为单位的浮点小数
import time # 引入time模块
ticks = time.time()
print("当前时间戳为:", ticks)
# 当前时间戳为: 1632676717.5455847
时间元组
| 序号 | 字段 | 属性 | 值 |
|---|---|---|---|
| 0 | 4位数年 | tm_year | 2008 |
| 1 | 月 | tm_mon | 1 到 12 |
| 2 | 日 | tm_mday | 1 到 31 |
| 3 | 小时 | tm_hour | 0 到 23 |
| 4 | 分钟 | tm_min | 0 到 59 |
| 5 | 秒 | tm_sec | 0 到 61 (60或61 是闰秒) |
| 6 | 一周的第几日 | tm_wday | 0到6 (0是周一) |
| 7 | 一年的第几日 | tm_yday | 1 到 366(儒略历) |
| 8 | 夏令时 | tm_isdst | -1, 0, 1, -1是决定是否为夏令时的旗帜 |
获取当前时间
从返回浮点数的时间戳方式向时间元组转换,只要将浮点数传递给如localtime之类的函数
import time
localtime = time.localtime(time.time())
print("本地时间为 :", localtime)
# 本地时间为 : time.struct_time(tm_year=2021, tm_mon=9, tm_mday=27, tm_hour=1, tm_min=24, tm_sec=5, tm_wday=0, tm_yday=270, tm_isdst=0)
获取格式化的时间
获取可读的时间模式的函数是asctime()
import time
localtime = time.asctime(time.localtime(time.time()))
print("本地时间为 :", localtime)
# 本地时间为 : Mon Sep 27 01:25:32 2021
格式化日期
time 模块的 strftime 方法来格式化日期
time.strftime(format[, t])
import time
# 格式化成2016-03-20 11:45:39形式
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
# 格式化成Sat Mar 28 22:24:24 2016形式
print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))
# 将格式字符串转换为时间戳
a = "Sat Mar 28 22:24:24 2016"
print(time.mktime(time.strptime(a, "%a %b %d %H:%M:%S %Y")))
'''
2021-09-27 01:28:18
Mon Sep 27 01:28:18 2021
1459175064.0
'''
python中时间日期格式化符号
- %y 两位数的年份表示(00-99)
- %Y 四位数的年份表示(000-9999)
- %m 月份(01-12)
- %d 月内中的一天(0-31)
- %H 24小时制小时数(0-23)
- %I 12小时制小时数(01-12)
- %M 分钟数(00-59)
- %S 秒(00-59)
- %a 本地简化星期名称
- %A 本地完整星期名称
- %b 本地简化的月份名称
- %B 本地完整的月份名称
- %c 本地相应的日期表示和时间表示
- %j 年内的一天(001-366)
- %p 本地A.M.或P.M.的等价符
- %U 一年中的星期数(00-53)星期天为星期的开始
- %w 星期(0-6),星期天为星期的开始
- %W 一年中的星期数(00-53)星期一为星期的开始
- %x 本地相应的日期表示
- %X 本地相应的时间表示
- %Z 当前时区的名称
- %% %号本身
获取某月日历
import calendar
cal = calendar.month(2016, 1)
print("以下输出2016年1月份的日历:")
print(cal)
'''
以下输出2016年1月份的日历:
January 2016
Mo Tu We Th Fr Sa Su
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
'''
Time 模块
Time 模块包含了以下内置函数,既有时间处理的,也有转换时间格式的
| 序号 | 函数及描述 |
|---|---|
| 1 | time.altzone 返回格林威治西部的夏令时地区的偏移秒数。如果该地区在格林威治东部会返回负值(如西欧,包括英国)。对夏令时启用地区才能使用。 |
| 2 | [time.asctime(tupletime]) 接受时间元组并返回一个可读的形式为”Tue Dec 11 18:07:14 2008”(2008年12月11日 周二18时07分14秒)的24个字符的字符串。 |
| 3 | time.clock( ) 用以浮点数计算的秒数返回当前的CPU时间。用来衡量不同程序的耗时,比time.time()更有用。 |
| 4 | [time.ctime(secs]) 作用相当于asctime(localtime(secs)),未给参数相当于asctime() |
| 5 | [time.gmtime(secs]) 接收时间戳(1970纪元后经过的浮点秒数)并返回格林威治天文时间下的时间元组t。注:t.tm_isdst始终为0 |
| 6 | [time.localtime(secs]) 接收时间戳(1970纪元后经过的浮点秒数)并返回当地时间下的时间元组t(t.tm_isdst可取0或1,取决于当地当时是不是夏令时)。 |
| 7 | time.mktime(tupletime) 接受时间元组并返回时间戳(1970纪元后经过的浮点秒数)。 |
| 8 | time.sleep(secs) 推迟调用线程的运行,secs指秒数。 |
| 9 | [time.strftime(fmt,tupletime]) 接收以时间元组,并返回以可读字符串表示的当地时间,格式由fmt决定。 |
| 10 | time.strptime(str,fmt=’%a %b %d %H:%M:%S %Y’) 根据fmt的格式把一个时间字符串解析为时间元组。 |
| 11 | time.time( ) 返回当前时间的时间戳(1970纪元后经过的浮点秒数)。 |
| 12 | time.tzset() 根据环境变量TZ重新初始化时间相关设置。 |
Time模块包含了以下2个非常重要的属性:
| 序号 | 属性及描述 |
|---|---|
| 1 | time.timezone 属性 time.timezone 是当地时区(未启动夏令时)距离格林威治的偏移秒数(>0,美洲<=0大部分欧洲,亚洲,非洲)。 |
| 2 | time.tzname 属性time.tzname包含一对根据情况的不同而不同的字符串,分别是带夏令时的本地时区名称,和不带的。 |
日历(Calendar)模块
此模块的函数都是日历相关的,例如打印某月的字符月历。
星期一是默认的每周第一天,星期天是默认的最后一天。更改设置需调用calendar.setfirstweekday()函数。模块包含了以下内置函数
| 序号 | 函数及描述 |
|---|---|
| 1 | calendar.calendar(year,w=2,l=1,c=6) 返回一个多行字符串格式的year年年历,3个月一行,间隔距离为c。 每日宽度间隔为w字符。每行长度为21* W+18+2* C。l是每星期行数。 |
| 2 | calendar.firstweekday( ) 返回当前每周起始日期的设置。默认情况下,首次载入 calendar 模块时返回 0,即星期一。 |
| 3 | calendar.isleap(year) 是闰年返回 True,否则为 False。>>> import calendar >>> print(calendar.isleap(2000)) True >>> print(calendar.isleap(1900)) False |
| 4 | calendar.leapdays(y1,y2) 返回在Y1,Y2两年之间的闰年总数。 |
| 5 | calendar.month(year,month,w=2,l=1) 返回一个多行字符串格式的year年month月日历,两行标题,一周一行。每日宽度间隔为w字符。每行的长度为7* w+6。l是每星期的行数。 |
| 6 | calendar.monthcalendar(year,month) 返回一个整数的单层嵌套列表。每个子列表装载代表一个星期的整数。Year年month月外的日期都设为0;范围内的日子都由该月第几日表示,从1开始。 |
| 7 | calendar.monthrange(year,month) 返回两个整数。第一个是该月的星期几的日期码,第二个是该月的日期码。日从0(星期一)到6(星期日);月从1到12。 |
| 8 | calendar.prcal(year,w=2,l=1,c=6) 相当于 **print calendar.calendar(year,w=2,l=1,c=6)**。 |
| 9 | calendar.prmonth(year,month,w=2,l=1) 相当于 print calendar.month(year,month,w=2,l=1) 。 |
| 10 | calendar.setfirstweekday(weekday) 设置每周的起始日期码。0(星期一)到6(星期日)。 |
| 11 | calendar.timegm(tupletime) 和time.gmtime相反:接受一个时间元组形式,返回该时刻的时间戳(1970纪元后经过的浮点秒数)。 |
| 12 | calendar.weekday(year,month,day) 返回给定日期的日期码。0(星期一)到6(星期日)。月份为 1(一月) 到 12(12月)。 |
待更新