- python3的字符串:
1.文本字符串(str)---->unicode
'' "" ''' ''' str()
2.二进制字符串(bytes)
b'' b"" b''' ''' bytes()
3.编码:
str--->bytes string.encode(encoding = 'utf-8')
4.解码:
bytes--->str bytestring.decode(encodeing = 'utf-8')
5.练习
s = 'python是最好的语言' bs = s.encode() print(type(bs)) print(bs) bs2 = bytes(s, encoding='utf-8') print(type(bs2)) print(bs2) s1 = bs2.decode() print(type(s1)) print(s1) s2 = str(bs2, encoding='utf-8') print(type(s2)) print(s2)
- 字符串方法补充
# 居中填充 s = 'python' s = s.center(20, '-') print(s) # 统计出现个数 print(s.count('th', 0, 3)) # 找到子串 '-------python-------' ind = s.find('th') print(ind) # 按进制输出 s = '{:b}'.format(10) print(s) s = '{:o}'.format(10) print(s) s = '{:x}'.format(10) print(s) import random # 字符串拼接 s = 'beautiful' l = list(s) random.shuffle(l) s = ''.join(l) print(s) s = ''.join(('haha', 'hehe', 'hihi')) print(s) s = ','.join('hello') print(s) # 替换 s = s.replace(',', '.') print(s) # 切割 res = s.split('.') print(res)
- 深复制和浅复制
import copy
# 对于非复合类型 深复制和浅复制无差别 a = 10 b = copy.copy(a) print(id(a)) print(id(b)) a = 20 print(a, b) # 对于可变复合类型 浅复制不会复制子对象,而深复制会 a = [1,2,[100, 200]] b = copy.copy(a) print(id(a)) print(id(b)) a[0] = 110 print(a) print(b) a[2][1] = 222 print(a) print(b) b = copy.deepcopy(a) print(id(a)) print(id(b)) a[0] = 1 print(b) a[2][1] = 333 print(a) print(b) print(id(a[2])) print(id(b[2]))
- 列表生成式
l = [] for i in range(100): if i % 2 == 0: l.append(i) print(l) l = [i*i for i in range(100) if i % 2 == 0] print(l)
''' 练习1:有字符串s1 = 'ABC' s2 = 'xyz' 生成一个列表,列表中的元素是['Ax', 'By', 'Cz'] ''' l = [x+y for x in 'ABC' for y in 'xyz'] print(l) s1 = 'ABC' s2 = 'xyz' l = [s1[i]+s2[i] for i in range(len(s1))] print(l) ''' 练习2:有列表l = ['Hello', 'EVERYone', 'goOd', 'AFTErNooN'] 使用一条语句将列表中变成由所有小写字母组成 ''' l = ['Hello', 'EVERYone', 'goOd', 'AFTErNooN'] l = [x.lower() for x in l] print(l)
- 生成器
l = [i for i in range(100)] print(l)
# 生成器:节省空间
g = (i for i in range(100))
print(g)
print(next(g))
print(next(g))
for x in g:
print(x, end=' ')
print()
- 字典(dict):
# 定义 d1 = {'name':'python', 'age':20} print(type(d1)) print(d1) d2 = dict(name='python', age=20) print(type(d2)) print(d2) d3 = dict([('name', 'python'), ('age', 20)]) print(type(d3)) print(d3) d4 = dict(zip(['name', 'age'], ['python', 20])) print(type(d4)) print(d4) # 通过key得到成员: key唯一的,不可变的 print(d4['name']) d4['name'] = 'guido' print(d4) # 获得所有的key, values, item print(d4.keys()) print(d4.values()) print(d4.items()) # 遍历 for k in d4.keys(): print(d4[k]) for k, v in d4.items(): print(k, v) for k in d4: # key print(k) # 增加 d4['height'] = 180 print(d4) d4.update(id=5, score=100) print(d4) # 删除 d4.pop('id') print(d4)
- 集合(set):无序的不重叠的可变的
去除重复
# 定义 st = {1,2,3,4} print(type(st)) print(st) # 去重 l = [1,2,3,3,2,34,1,23] l = list(set(l)) print(l) for i in st: print(i) st.add(100) print(st) st.pop() print(st) st.remove(100) print(st) st2 = {2,1,8,9,4} print(st & st2) # 交集 print(st | st2) # 并集 print(st - st2) # 差集 print(st ^ st2) # 交叉差集