本章内容
1、模块
2、数据类型与数据运算
3、进制
4、byte 与 string 的互相转换
5、列表
6、元组
7、字符串操作
8、字典
一、模块
Python 把某些常用的定义存放在文件中,为一些脚本或者交互式的解释器实例使用,这个文件被称为模块。模块是一个包含所有你定义的函数和变量的文件,其后缀名是.py。模块可以被别的程序引入,以使用该模块中的函数等功能。Python中有两种模块,一种是内置模块,也称为标准库,另一种是自定义模块,称为第三方库
1、标准库
标准库无需独立安装,可以直接使用。比如sys模块和os模块。
import sys
print(sys.path,"\n")
print(sys.argv)
import os
cmd_com = os.system("dir")
print(cmd_com)
import os
os.mkdir("new_dir")
#创建新目录
2、第三方库
在Python中,安装第三方模块,是通过setuptools这个工具完成的。Python有两个封装了setuptools的包管理工具:easy_install
和pip
。目前官方推荐使用pip
。在命令提示符窗口下尝试运行pip,现在,让我们来安装一个第三方库——Python Imaging Library,这是Python下非常强大的处理图像的工具库。一般来说,第三方库都会在Python官方的pypi.python.org网站注册,要安装一个第三方库,必须先知道该库的名称,可以在官网或者pypi上搜索,比如Python Imaging Library的名称叫PIL,因此,安装Python Imaging Library的命令就是:
pip install PIL
模块的调用:
模块在调用时,会首先从当前文件目录下寻找模块,可以将模块直接放到python安装文件的site-package 目录下直接放在当前文件夹中,这样就可以直接调用。
import login
或者在当前目录下创建一个文件夹用于放置模块,命名为module,将需要的模块放在module文件夹下,同时在该文件夹下创建 _init_.py 文件用于表示该文件夹是一个模块库。
需要调用module模块库中的login 模块,可以用下面的方法:
import module.login
或者
1 from module import login
当导入的模块中有多个函数,比如 login 中分别定义了 func_1 和 func_2 ,就可以用下面的方法分别调用对应的函数
from module import login
login.func_1()
login.func_2()
如果模块名过长,比如TemperatureConversion.py ,每次都要调用很麻烦,可以使用下面的方法简化调用过程
from module import TemperatureConversion as tc
tc.fun_1()
tc.fun_2()
示例:通过PIL模块库中Image 模块读取并显示图片
from PIL import Image
im = Image.open("图片.png")
im.show()
补充:pyc文件
pyc是一种二进制文件,是由py文件经过编译后,生成的文件,是一种byte code,py文件变成pyc文件后,加载的速度有所提高,而且pyc是一种跨平台的字节码,是由python的虚拟机来执行的,这个是类似于JAVA或者.NET的虚拟机的概念。pyc的内容,是跟python的版本相关的,不同版本编译后的pyc文件是不同的。
二、数据类型与数据运算
1、python支持四种不同的数据类型 int整型、bool布尔型、float浮点型、complex复数
var1 = 10; #表示整型
var2 = True #表示布尔型
var3 = 12.34;#表示浮点型
var4 = 123j #复数
var5 = 123+45j #复数
2、科学记数法:用 E(e) 表示 10的次方 。
3、基础运算
(1)加: +
1 + 1
(2)减: -
1 - 1
(3)乘: *
1 * 1
(4)除:
普通除法: /
9 / 2
地板除: // (结果只取整数部分)
9 // 2
取余数: %
9 // 2
(5)幂运算: **
2 ** 3
三、进制
常用转换表如下:
二进制 | 八进制 | 十进制 | 十六进制 |
0000 | 0 | 0 | 0 |
0001 | 1 | 1 | 1 |
0010 | 2 | 2 | 2 |
0011 | 3 | 3 | 3 |
0100 | 4 | 4 | 4 |
0101 | 5 | 5 | 5 |
0110 | 6 | 6 | 6 |
0111 | 7 | 7 | 7 |
1000 | 10 | 8 | 8 |
1001 | 11 | 9 | 9 |
1010 | 12 | 10 | A |
1011 | 13 | 11 | B |
1100 | 14 | 12 | C |
1101 | 15 | 13 | D |
1110 | 16 | 14 | E |
1111 | 17 | 15 | F |
表示方法: 0开始表示8进制,0x开始表示16进制
具体转换方法见链接:
https://jingyan.baidu.com/article/495ba84109665338b30ede98.html
四、byte 与 string 的互相转换
1、bytes主要是给在计算机看的,string主要是给人看的
2、中间有个桥梁就是编码规则,现在大趋势是utf8
3、bytes对象是二进制,很容易转换成16进制,例如\x64
4、string就是我们看到的内容,例如'abc'
5、string经过编码encode,转化成二进制对象,给计算机识别
6、bytes经过反编码decode,转化成string,让我们看,但是注意反编码的编码规则是有范围,\xc8就不是utf8识别的范围
五、列表
1、列表的创建
names = ["赵","钱","孙","李","周","吴","郑","王"]
print(names)
>>>['赵', '钱', '孙', '李', '周', '吴', '郑', '王']
2、通过下标取出列表中的元素
(1)取出列表中的第一个元素
names = ["赵","钱","孙","李","周","吴","郑","王"]
print(names[])
>>>赵
#列表的下标是从 0 开始计算的。
(2)取出列表中的最后一个元素
names = ["赵","钱","孙","李","周","吴","郑","王"]
print(names[-])
>>>王
3、列表的切片
(1)取出前三个元素
names = ["赵","钱","孙","李","周","吴","郑","王"]
print(names[:])
>>>['赵', '钱', '孙']
#[ a : b ] 不包含b,且a 不能大于b,如果a为0,或者b为最后一个元素的下标,都可以省略。
(2)取出最后两个元素
names = ["赵","钱","孙","李","周","吴","郑","王"]
print(names[-:])
>>>['郑', '王']
4、向列表中追加元素
names = ["赵","钱","孙","李","周","吴","郑","王"]
names.append("冯")
print(names)
>>>['赵', '钱', '孙', '李', '周', '吴', '郑', '王', '冯']
#默认追加到列表的最后一位
5、向指定位置插入元素
names = ["赵","钱","孙","李","周","吴","郑","王"]
names.insert(2,"冯")
print(names)
>>>['赵', '钱', '冯', '孙', '李', '周', '吴', '郑', '王']
#insert()包含两个参数,第一个参数是指定插入的位置,第二个参数是插入的元素
6、更改指定的元素
names = ["赵","钱","孙","李","周","吴","郑","王"]
names[2] = "蒋"
print(names)
>>>['赵', '钱', '蒋', '李', '周', '吴', '郑', '王']
7、删除指定的元素
(1)remove()
names = ["赵","钱","孙","李","周","吴","郑","王"]
names.remove("李")
print(names)
>>>['赵', '钱', '孙', '周', '吴', '郑', '王']
(2)del
names = ["赵","钱","孙","李","周","吴","郑","王"]
del names[2]
print(names)
>>>['赵', '钱', '李', '周', '吴', '郑', '王']
(3)pop()
names = ["赵","钱","孙","李","周","吴","郑","王"]
names.pop(5)
print(names)
>>>['赵', '钱', '孙', '李', '周', '郑', '王']
# pop() 需要一个参数,当不指定参数时,默认删除最后一个元素
8、查找元素的位置
names = ["赵","钱","孙","李","周","吴","郑","王"]
print(names.index("孙"))
>>>2
#默认返回从0起第一个指定参数的位置
9、统计某一个元素出现的次数
names = ["赵","钱","孙","李","周","吴","郑","王"]
print(names.count("孙"))
>>>1
10、清空列表
names = ["赵","钱","孙","李","周","吴","郑","王"]
names.clear()
print (names)
>>>[]
11、将列表翻转
names = ["赵","钱","孙","李","周","吴","郑","王"]
names.reverse()
print (names)
>>>['王', '郑', '吴', '周', '李', '孙', '钱', '赵']
12、将列表中的元素按ASCII码排序
names = ["赵","钱","孙","李","周","吴","郑","王"]
names.sort()
print (names)
>>>['吴', '周', '孙', '李', '王', '赵', '郑', '钱']
13、用一个列表来扩展原列表
names = ["赵","钱","孙","李","周","吴","郑","王"]
names_2 = ["冯","陈","褚","卫","蒋","沈","韩","杨",]
names.extend(names_2)
print (names)
>>>['赵', '钱', '孙', '李', '周', '吴', '郑', '王', '冯', '陈', '褚', '卫', '蒋', '沈', '韩', '杨']
14、计算列表中元素的总个数
names = ["赵","钱","孙","李","周","吴","郑","王"]
print (len(names))
>>>8
15、复制列表
(1)浅复制
names = ["赵","钱","孙","李","周","吴","郑","王"]
names_2 = names.copy()
print (names_2)
>>>['赵', '钱', '孙', '李', '周', '吴', '郑', '王']
浅复制只复制列表的第一层,并且第一层是互相独立的,修改其中任何一个列表,另外的列表都不会受到影响。
names = ["赵","钱","孙","李","周","吴","郑","王"]
names_2 = names.copy()
names_2[0] = "杨"
names[6] = "陈"
print(names)
print (names_2)
>>>
['赵', '钱', '孙', '李', '周', '吴', '陈', '王']
['杨', '钱', '孙', '李', '周', '吴', '郑', '王']
但是如果列表中还嵌套着下一级列表,则浅复制之后的第二级及以上的列表如果被修改,其他的列表都会跟着改变,因为第二级复制的只是内存地址,当修改了第二级列表,实际上是修改了内存中的值。
names = ["赵","钱","孙","李","周","吴","郑","王",["冯","陈","褚","卫"]]
names_2 = names.copy()
names_2[8][2] = "杨"
names[8][3] = "韩"
print(names)
print (names_2)
>>>
['赵', '钱', '孙', '李', '周', '吴', '郑', '王', ['冯', '陈', '杨', '韩']]
['赵', '钱', '孙', '李', '周', '吴', '郑', '王', ['冯', '陈', '杨', '韩']]
16、列表的嵌套
names = ["赵","钱","孙","李","周","吴","郑","王"]
names_2 = ["冯","陈","褚","卫","蒋","沈","韩","杨"]
names[7] = names_2
print(names)
5 print(names[7][5]) >>>['赵', '钱', '孙', '李', '周', '吴', '郑', ['冯', '陈', '褚', '卫', '蒋', '沈', '韩', '杨']]
沈
17、列表的循环
(1)普通循环
names = ["赵","钱","孙","李","周","吴","郑","王"]
for each in names:
print(each,end = ' ')
>>>赵 钱 孙 李 周 吴 郑 王
#end = " " 表示每一次打印完姓氏之后,以end 指定的内容结尾,比如这里就是以空格结尾,如果不加end = " ... " ,则默认是换行
(2)切片循环
names = ["赵","钱","孙","李","周","吴","郑","王"]
for i in names[0:-1:2]:
print(i,end = "")
>>>赵孙周郑
六、元组
元组实际上是一个不可以修改的列表,也称作只读列表,它只有两种用法:
(1)count()
name = ("赵","钱","孙","李","周","吴","郑","王","李","郑","王")
print(name.count("李"))
>>>2
(2) index()
name = ("赵","钱","孙","李","周","吴","郑","王","李","郑","王")
print(name.index("李"))
>>>3
#默认返回从0起第一个指定参数的位置
七、字符串操作
1、首字母大写
strings = "i love you"
print(strings.capitalize())
>>>I love you
#只把第一个字母大写
2、统计字符串中字符的个数
strings = "i love you"
print(strings.count("o"))
>>>2
3、字符串补齐
(1)两侧补齐
strings = "i love you"
print(strings.center(50,"-"))
>>>--------------------i love you--------------------
#一共打印50个字符,将strings放在中间,两边用”-“补齐
(2)左侧补齐
strings = "I Love You"
print(strings.rjust(20,"-"))
>>>----------I Love You
(3)右侧补齐
strings = "I Love You"
print(strings.ljust(20,"-"))
>>>I Love You----------
4、字符串转换为二进制编码
strings = "i love you"
print(strings.encode())
>>>b'i love you'
5、判断字符串是否以指定字符结尾
strings = "i love you"
print(strings.endswith("you"))
>>>True
6、查找字符串中指定字符的第一个索引
strings = "i love you"
print(strings.find("o"))
>>>3
7、字符串切片
strings = "i love you"
print(strings[0:6])
>>>i love
8、字符串格式化
strings = "{a} love {b}"
print(strings.format(a = 'you' , b = "i"))
>>>you love i
9、用字典进行格式化
strings = "{a} love {b}"
print(strings.format_map({"a":"you","b":"i"}))
>>>you love i
10、查找元素的索引
strings = "i love you"
print(strings.index("o"))
>>>3
#默认显示从0开始第一个指定元素的索引
11、判断字符串是否是阿拉伯数字或者英文字母组成
strings = "i love you 1314"
print(strings.isalnum())
>>>False
strings = "iloveyou1314"
print(strings.isalnum())
>>>True
12、判断字符串是否为纯英文组成
strings = "iloveyou"
print(strings.isalpha())
>>>True
#只能是英文字母,不能有数字,空格等
13、判断字符串是否为十进制
strings = ""
print(strings.isdecimal())
>>>True
14、判断字符串是否为整数
strings = ""
print(strings.isdigit())、
>>>True
15、判断字符串是否为合法的标识符(变量名)
strings = "MR1314"
print(strings.isidentifier())
>>>True
16、判断字符串为否为全部小写
strings = "i love you"
print(strings.islower())
>>>True
17、判断字符串为否为全部大写
strings = "I LOVE YOU"
print(strings.isupper())
>>>True
18、判断字符串是否为纯数字(不包括小数)
strings = ""
print(strings.isnumeric())
>>>True
19、判断字符串是否为标题格式
strings = "I Love You"
print(strings.istitle())
>>>True
20、把字符串重复插入另一个字符串的每两个字符中间
strings = "+"
print(strings.join(""))
>>>1+2+3
21、大小写单向转换
(1)大写转换为小写
strings = "I Love You"
print(strings.lower())
>>>i love you
(2)小写转化为大写
strings = "I Love You"
print(strings.upper())
>>>I LOVE YOU
22、去除字符串外面的空格
(1)去除两端的空格
strings = " I Love You "
print(strings.strip())
>>>I Love You
(2)去除左侧的空格
strings = " I Love You "
print(strings.lstrip())
>>>I Love You
(3)去除右侧的空格
strings = " I Love You "
print(strings.rstrip())
>>> I Love You
23、根据指定转换关系表对字符串进行转换
strings = "abcdefghijklmn"
p = str.maketrans("abcdefg","")
print(strings.translate(p))
>>>1234567hijklmn
24、字符串替换
strings = "abcdefghijklmn"
print(strings.replace('b',"B"))
>>>aBcdefghijklmn
25、字符串索引
(1)普通索引
strings = "abcdefghijklmbn"
print(strings.find('b'))
>>>1
(2)从右侧开始索引
strings = "abcdefghijklmbn"
print(strings.rfind('b'))
>>>13
26、字符串分割
(1)自定义分割
strings = "a b c d e fghi jklmbn"
print(strings.split(" "))
>>>['a', 'b', 'c', 'd', 'e', 'fghi', 'jklmbn']
#分割后的元素放入列表中
(2)换行符分割
strings = "a \n b c d e fghi jklmbn"
print(strings.splitlines())
>>>['a ', ' b c d e fghi jklmbn']
27、判断字符串是否以指定内容为开头
strings = "a b c d e fghi jklmbn"
print(strings.startswith("a"))
>>>True
28、大小写互换
strings = "aBcdEFSKHmbn"
print(strings.swapcase())
>>>AbCDefskhMBN
29、字符串标题化
strings = "i love you"
print(strings.title())
>>>I Love You
八、字典
1、字典的创建
capital = {"China":"BeiJing","America":"NewYork","England":"London","France":"Paris"}
print(capital)
>>>{'America': 'NewYork', 'England': 'London', 'France': 'Paris', 'China': 'BeiJing'}
#字典是无序的,也没有下标
2、查找字典中的key对应的value
capital = {"China":"BeiJing","America":"NewYork","England":"London","France":"Paris"}
print(capital["China"])
>>>BeiJing
3、更改字典的key对应的value
capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
capital["America"] = "NewYork"
print(capital)
>>>{'China': 'BeiJing', 'America': 'NewYork', 'France': 'Paris', 'England': 'London'}
4、在字典中添加新的key-value
capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
capital["Kerea"] = "Seoul"
print(capital)
>>>{'China': 'BeiJing', 'France': 'Paris', 'Kerea': 'Seoul', 'America': 'Washington', 'England': 'London'}
5、删除字典中的某一个key-value
(1)del
capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
del capital["France"]
print(capital)
>>>{'England': 'London', 'China': 'BeiJing', 'America': 'Washington'}
(2)pop()
capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
capital.pop("France")
print(capital)
>>>{'China': 'BeiJing', 'America': 'Washington', 'England': 'London'}
#与列表中的pop不同,由于字典是无序的,所以字典在使用pop时必须指定参数
(3) popitem()
capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
capital.popitem()
print(capital)
>>>{'China': 'BeiJing', 'America': 'Washington', 'England': 'London'}
#popitem()是随机删除字典中的key-value
6、查找字典中的key
capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
print(capital.get("Kerea"))
>>>None
#当查找的key不存在时返回None,不会报错
capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
print(capital.get("China"))
>>>BeiJing
7、多级字典的嵌套及操作
(1)修改二级字典中的value
district ={
"JiangSu":{"Nanjing":["LiuHe","PuKou"]},
"AnHui":{"HeFei":["YaoHai","BaoHe"]},
"HuBei":{"WuHan":["HongShan","WuChang"]}
}
district["HuBei"]["WuHan"][0] = "HanKou"
print(district)
>>>{'HuBei': {'WuHan': ['HanKou', 'WuChang']}, 'JiangSu': {'Nanjing': ['LiuHe', 'PuKou']}, 'AnHui': {'HeFei': ['YaoHai', 'BaoHe']}}
8、设置字典的默认值
capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
capital.setdefault("America","Soule")
print(capital)
>>>{'England': 'London', 'France': 'Paris', 'America': 'Washington', 'China': 'BeiJing'}
#寻找字典中的key,已存在则更改相应的value,不存在则添加新的key-value
9、更新字典
capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
capital2 = {"China":"BeiJing","America":"Moscow","England":"London","France":"Paris","Kerea":"Soule"}
capital.update(capital2)
print(capital)
>>>{'France': 'Paris', 'England': 'London', 'China': 'BeiJing', 'America': 'Moscow', 'Kerea': 'Soule'}
#用字典capital2 来更新capital,有交叉则覆盖,多余的就新添加进去
10、将字典转换为由元组组成的列表
capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
print(capital.items())
for key,value in capital.items():
print (key,value)
>>>
dict_items([('America', 'Washington'), ('China', 'BeiJing'), ('England', 'London'), ('France', 'Paris')])
America Washington
China BeiJing
England London
France Paris
11、创建一个不同key 对应相同 value 的字典
capital= dict.fromkeys([1,2,3],"Amazing")
print(capital)
>>>{1: 'Amazing', 2: 'Amazing', 3: 'Amazing'}
#无论value是多少,是字符串还是列表,都被组合成一个值,对应不同的key,如果修改其中一个的value,其他的value都会跟着更改。
12、字典的循环
capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
for i in capital:
print(i,":",capital[i])
>>>
China : BeiJing
America : Washington
France : Paris
England : London