python学习笔记02

字典,字符串,编码解码

提示:

python中所有类型都是对象

其中整形,字符串,元组等不可变类型
列表,字典可变类型

所谓可变和不可变顾名思义,就是一个对象在内存中分配地址后,该地址中的内容是否可以改变。可以在python中通过id()函数查看变量的地址
这里不详细解释,有问题自己 百度一下吧,当然也可以问我哦。

一. 字典

何谓字典,也许听说过一个词语叫键值对,就是一一映射的关系,python中将这种关系封装起来为一个数据类型为
字典:比如我叫海涛海涛就是,我本人就是

1. 创建

1
2
3
4
# 使用**{}**来表示一个字典,
# 使用 **:** 来分隔**键**和**值**,
# 使用 **,** 分隔开一组一组的键值对。
dic = {'name':'haitao', 'age':12, 'hobby':{'gril_name':'tiechui','gril_age':'100'}, 'is_handsome':True}
  • 注意:键值对在字典中的存储是乱序存储的,不像列表和元组是严格按照顺序存储,依旧是说不能通过索引下标访问列表元素。
1
2
3
4
5
# 通过工厂函数创建字典,列表,元组
a = list() # list()即是工厂函数,表示创建了一个空列表,
a = list([1, 2, 3]) # 创建的列表为[1, 2, 3],这里[]也可以换为()
dic = dict((('name','zhangjitao'),)) # dict()为工厂函数,函数内的括号表示输入的初值,最里面的括号表示一对键值对。
dic = dict((['name','zhangjitao'],)) # 最后加一个逗号是习惯,今后会用得到。

2. 查询(访问)

1
2
3
4
print(dic['name'])   # 通过键查找
print(dic.keys()) # 打印所有键,返回一个迭代类型,不是列表类型,通过list()转换为列表
print(list(dic.values())) # 打印所有键,返回一个迭代类型,通过list()转换为列表
print(dic.items()) # 返回键值对

3. 修改

1
2
3
4
dic['name'] = 'haitao'  # 该键("name")已有则修改,没有则添加

dic4 = {'sex':'boy','age':33,'hobby':'skfla'}
dic.update(dic4) # 已有则覆盖,没有就加入,类似list.extend()

4. 删除

1
2
3
4
5
6
7
8
del dic['name'] # 通过del关键字删除
dic.clear() # 清空

dic.pop('age') # 删除,有返回值

a = dic.popitem() #随机删除一个

del dic #删除字典

5. 其他操作涉及到的方法

1
2
3
4
5
6
7
8
9
10
11
12
dic = dict.fromkeys(['host1','host2','host3'],'test') #列表中每一个都为键,后一个为值
print(dic) # 执行结果: {'host1': 'test', 'host2': 'test', 'host3': 'test'}
dic['host2'] = 'abc' #修改操作
print(dic) #执行结果:{'host1': 'test', 'host2': 'abc', 'host3': 'test'}
---------------------------------------------------------------------------------------------------------------------------
dic = dict.fromkeys(['host1','host2','host3'],['test1','test2']) #列表中每一个都为键,后一个为值
print(dic) #{'host1': None, 'host2': None, 'host3': None}

dic['host2'][1] = 'abc'
print(dic) #执行结果:# {'host1': ['test1', 'abc'], 'host2': ['test1', 'abc'], 'host3': ['test1', 'abc']},都改了。。浅拷贝。
# 这种方法建立的字典所有的值都指向一个列表所在的空间,所以改变一个 之后都会改变,这种现象学名叫--浅拷贝--
# 因此不建议使用这种方式进行字典的初始化。

6. 字典嵌套(这个没什么好说的。。)。

二. 字符串

顾名思义,就是一串字符

1. 乘法,切片操作

1
2
3
4
# 乘法操作
print("hello"*5) # 执行结果:hellohellohellohellohello:输出了五个hello
# 切片
print('hello world'[2:]) # 执行结果: llo world

这里说一下,无论是字符串,还是列表,元组,他们的下标都是从0开始的,而且切片原则是–包头不包尾,所有的涉及到下标的操作方法基本上都是–包头不包尾,java中也是

2. 关键字in 判断

1
2
print('hello' in 'hello word') # 判断hello是否在hello world中,,执行结果:True
print(123 in [2, 3, 4, 5, 123]) # 123是否在列表中。。执行结果:True

3. 格式化输出

  • 第一种方法
    1
    print('name:%s,score:%d' % ('hai tao', 2)) # name:hai tao,score:2

输出格式如上,记住就行,有过c基础的应该能看懂

  • 第二种方法
    1
    2
    3
    4
    5
    st = 'hello kitty {name} is {age}'
    print(st)
    # 执行结果:hello kitty {name} is {age}
    print(st.format(name='hai tao', age=37)) # 调用st字符对象的format函数传值。
    # 执行结果:hello kitty hai tao is 37

4. 字符串拼接

  • 第一种方法

    1
    2
    3
    4
    a = '123'
    b = 'abc'
    c = a+' '+b # 效率低
    print(c) # 通过+号来对字符串进行连接,执行结果:123 abc
  • 第二种方法

    1
    2
    3
    4
    a = '123'
    b = 'abc'
    c = '***'.join([a, 'ABC', b]) # 通过前面的字符拼接,这里的“***”可以替换为任意字符
    print(c) # 执行结果:123***ABC***abc

通常使用第二种方法进行字符串的连接,效率高。注意:join中的传入的参数为一个列表

5. String的内置方法

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
st = 'hello kitty {name} is {age}'
print(st.count('l')) # 统计元素个数
# 执行结果:2
print(st.capitalize()) # 首字母大写,不改变原来字符串
# 执行结果:Hello kitty {name} is {age}
print(st.center(50, '-')) # 居中,只能是字符,不能是空格或者字符串
# 执行结果:-----------hello kitty {name} is {age}------------
print(st.endswith('ty')) # 以什么结尾
# 执行结果:False
print(st.startswith('h')) # 以什么开头 True 很重要,文件操作,判断是否为想要的内容
# 执行结果:True
print(st.expandtabs(20)) # \t
# 执行结果:hello kitty {name} is {age}
print(st.find('e')) # 寻找字符,返回其索引值,没有返回-1
# 执行结果:1
print(st.format(name='hai tao', age=37)) # 格式化输出的另一个方式, 赋值方式
# 执行结果:hello kitty hai tao is 37
print(st.format_map({'name':'zhangjitao','age':37})) # 格式化输出,传入字典
# 执行结果:hello kitty zhangjitao is 37
print(st.index('e')) # 跟find一样,找不到就报错
# 执行结果:1
print('ert456'.isalnum()) # 只包含字母和数字(汉字也行)就返回true
# 执行结果:True
print('023452'.isdecimal()) # 是否为十进制数是就返回True
# 执行结果:True
print('234'.isdigit()) # 判断是否为数字True
# 执行结果:True
print('234514'.isnumeric()) # 判断是否为数字True
# 执行结果:True
print('24aslkjf'.isidentifier()) # 检测是否为非法变量
# 执行结果:False
print('abc'.islower()) # 检验是否为小写(全小写)
# 执行结果:True
print('A'.isupper()) # 检验是否为全大写
# 执行结果:True
print('ABC'.isspace()) # 检验是否为空格
# 执行结果:False
print('Istitle i'.istitle()) # 判断每个单词首字符是否大写
# 执行结果:False
print('Alskd'.lower()) # 大写变小写
# 执行结果:alskd
print('Alskd'.upper()) # 小写变大写
# 执行结果:ALSKD
print('Alskd'.swapcase()) # 大写变小写,小写变大写,反转
# 执行结果:aLSKD
print('Alskd'.ljust(50, '*')) # 在左侧
# 执行结果:Alskd*********************************************
print('Alskd'.rjust(50, '*')) # 在右侧
# 执行结果:*********************************************Alskd
print(' Alsk d '.strip()) # 开头结尾的空格,换行去掉
# 执行结果:Alsk d
print(' Alsk d '.lstrip()) # 开头的空格,换行去掉
# 执行结果:Alsk d
print(' Alsk d '.rstrip()) # 结尾的空格,换行去掉
# 执行结果: Alsk d
print('My title'.replace('title', 'lession')) # 替换内容,参数可控制替换次数
# 执行结果:My lession
print('My title'.rfind('t')) # 从右往左找,返回其索引值
# 执行结果:5
print('My title'.split(' ')) # 分割,返回一个列表
# 执行结果:['My', 'title']
print('My title'.rsplit(' ', 1)) # 从右开始分割
# 执行结果:['My', 'title']
print('My title'.title()) # 每个单词首字符大写
# 执行结果:My Title

三. 编码与解码

1. 背景

编码与解码encode and decode
二进制
–>ASCII:只能存英文和拉丁字符,一个字符占一个字节,8位
——->gb2312:只能6700个中文,1980
——–>gbk1.0:存了2万多字符,1995
———->gb18030:27000中文,2000

———->unicode(万国码,一个编码标准):utf-32:一个字符占4个字节
———->unicode(万国码,一个编码标准):utf-16:一个字符占2个字节或者两个以上,65535
———->unicode(万国码,一个编码标准):utf-8:(可变长的),一个英文用ASCII存,一个中文3个字节

2. python3中的编码解码

1
2
3
4
5
6
7
8
9
10
import chardet,sys
print(sys.getdefaultencoding()) # 系统默认编码 utf-8
s = "I am 海涛!"
print("初始字符:%s" % (s,)) # 初始字符。 执行结果:I am 海涛!
s = s.encode('gbk') # 编码成为gbk码,参数为要编成的码
print(s) # 执行结果:b'I am \xba\xa3\xcc\xce\xa3\xa1'
s = s.decode('gbk') # 解码为系统默认编码,参数为初始的编码,解码成字符串
print(s) # 执行结果:I am 海涛!
s = s.encode('utf-8') # 编码成utf-8 bytes格式,
print(s) # 执行结果:b'I am \xe6\xb5\xb7\xe6\xb6\x9b\xef\xbc\x81'

encode编码时将数据转换成bytes格式
decode解码时将bytes转换成字符串

0%