Python学习笔记


Python学习笔记

一、字符串

1. 获取字符串的数字编码


ord('字符串')

2. 整数编码转换为字符串


chr(66)

3. 字符串转换为字节码 bytes


"字符串".encode('utf-8')

4. 字节码转换为字符串


b"abc".decode('utf-8')

5. 获取字符串长度


len('str中文')

6. 字符串格式化


"My name is %s, code is %d" % ('json', 100)

7. 截取字符串(切片)


str[0:3]

二、列表和元组

1. 初始化一个列表


classmates = []

2. 计算列表元素个数


len(classmates)

3. 添加元素


classmates.append('Adam')

4. 插入元素


classmates.insert(1, 'Jack')

5. 删除末尾的元素


classmates.pop()

6. 元组(不可变的列表)


classmates = ('Michael', 'Bob', 'Tracy')

7. 遍历列表


names = ['Michael', 'Bob', 'Tracy']
for name in names:
    print(name)

8. 取一部分(切片)


classmates[0:3]

三、字典(dist)

1. 创建


d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}

2. 判断 key 是否存在


 'Bob' in d

3. 获取某个元素


d['Bob']
d.get('Thomas') 

4. 删除一个元素


d.pop('Bob')

四、 集合

1. 创建集合


s = set([1, 2, 3])

2. 添加元素


add(4)

3. 删除元素


remove(4)

4. 取交集


s1 & s2

5. 取并集


s1 | s2

五、高级特性