列表、元组、字典、字符串、编码与解码
``
列表 |
1、列表的定义
定义格式:list1 = [e1,e2,e3,e4...]
说明:1、空列表用[]表示
2、列表中可以存储任意类型的数据
3、从左到右索引依次为:0、1、2、3....
4、从右往左索引依次为:-1、-2、-3、-4...
特点:
1、元素可重复
2、有序的,通过索引取
3、可变
2、根据列表索引获取元素
list1 = ['a', 'b', 'c']
print(list1[0]) # a
print(list1[1]) # b
print(list1[2]) # c
# print(list1[3]) # 报错,IndexError: list index out of range
print(list1[-1]) # c
3、列表的切片操作
list2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
print(list2[0]) # a 取第一个元素
print(list2[-1]) # h 取最后一个元素
print(list2[1:5]) # ['b','c','d','e'],从左到右取索引位置1-4的元素
print(list2[1:5:2]) # ['b','d'],从左到右取索引位置1-4的元素,每隔两个取一个
print(list2[1:]) # ['b', 'c', 'd', 'e', 'f', 'g', 'h'],取从左到右取索引位置1-末尾的元素
print(list2[-1:-5:-2]) # ['h','f'] 从右向左,每隔两个取一个
print(list2[::-1]) # 列表降序
4、列表的查找元素
# in和not in
print('a' in ['a', 'b', 'c']) # True
print('a' not in ['a', 'b', 'c']) # False
# count(value) -> integer
list1 = ['a', 'b', 'c', 'c', 'a', 'a']
print(list1.count('a')) # 3
# index(value, start=None, stop=None) -> integer 查找元素第一次出现的索引位置,找不到报错
list1 = ['a', 'b', 'c', 'c', 'a', 'a']
print(list1.index('b')) # 1
print(list1.index('c')) # 2
# print(list1.index('d')) # ValueError: 'd' is not in list
5、列表添加元素
# append(object) -> None 在列表的末尾添加元素
list1 = ['牛奶', '面包', '辣条']
list1.append('aa')
print(list1) # ['牛奶', '面包', '辣条', 'aa']
# insert(index,object) -> None 在指定的位置插入元素,index超过列表长度时,在末尾插入
list1 = ['牛奶', '面包', '辣条']
list1.insert(1, 'b')
print(list1) # ['牛奶', 'b', '面包', '辣条']
list1.insert(6, 'a')
print(list1) # ['牛奶', 'b', '面包', '辣条', 'a']
# + 合并两个列表
print(['a', 'b'] + ['c', 'd']) # ['a', 'b', 'c', 'd']
# extend(iterable) -> None 追加一个序列的值到列表中
list1 = ['a', 'c']
list2 = ['c', 'd']
list1.extend(list2)
print(list1) # ['a', 'c', 'c', 'd']
6、列表删除元素
# pop(index) -> item,根据索引删除元素,默认删除最后一个元素,返回删除的元素值,索引不存报错
list1 = ['牛奶', '面包', '辣条', '方便面', '方便面']
value = list1.pop()
print(value, list1) # 方便面 ['牛奶', '面包', '辣条', '方便面']
value = list1.pop()
print(value, list1) # 方便面 ['牛奶', '面包', '辣条']
value = list1.pop(0)
print(value, list1) # 牛奶 ['面包', '辣条']
# value = list1.pop(2) # IndexError: pop index out of range
# remove(object) -> None 删除指定的元素,object不存在报错
list1 = ['牛奶', '面包', '辣条', '方便面', '方便面']
value = list1.remove('方便面')
print(value, list1) # None ['牛奶', '面包', '辣条', '方便面']
# list1.remove('aaa') # ValueError: list.remove(x): x not in list
# del 根据索引删除元素,索引不存在就报错,或者删除对象
list1 = ['牛奶', '面包', '辣条', '方便面', '方便面']
del list1[1]
print(list1) # ['牛奶', '辣条', '方便面', '方便面']
# del list1[6] # IndexError: list assignment index out of range
del list1 # 删除对象,释放内存
# clear() 清空列表的内容
list1 = ['a','b','c']
list1.clear()
print(list1) # []
7、列表修改元素
list1 = ['牛奶', '面包', '辣条', '方便面', '方便面']
list1[0] = 'aa'
print(list1) # ['aa', '面包', '辣条', '方便面', '方便面']
list1[1:3] = ['dd']
print(list1) # ['aa', 'dd', '方便面', '方便面']
8、其他内置函数
# sort(key=None, reverse=False) -> None ,排序,reverse=False 默认升序
list1 = ['d','b','c','a']
list1.sort()
print(list1) # ['a', 'b', 'c', 'd']
list1.sort(reverse=True)
print(list1) # ['d', 'c', 'b', 'a']
# reverse() -> None ,反转
list1 = ['d', 'c', 'b', 'a']
list1.reverse()
print(list1) # ['a', 'b', 'c', 'd']
9、购物程序
# __author: 杜幼志
# date: 2023-03-25
# 定义商品列表
good_list = [['iphone 6s', 5800], ['mac bool', 9000], ['coffee', 9], ['python book', 90], ['biycle', 1500]]
# 定义用户购买商品列表
shopping_list = []
# 定义用户的金钱
salary = 0
while True:
money = int(input('请输入你的充值金额:'))
if money > 0:
salary += money
print('充值成功,当前余额为:{}元'.format(salary))
break
else:
print('充值金额必须大于0')
while True:
print('购物商城'.center(50, '-'))
for i, good in enumerate(good_list,1):
print('\t{}. {} {}'.format((i), good[0], good[1]))
choice = input('请选择(1-5,退出:q或Q)>>>')
if choice.isdigit():
choice = int(choice)
if choice in [i for i in range(1, len(good_list) + 1)]:
# 获取要购买的商品名称
good_name = good_list[choice - 1][0]
# 获取要购买商品的金额
good_money = good_list[choice - 1][1]
# 判断扣除之后余额是否>0,>0则添加到购物车,否则不添加
if salary - good_money >= 0:
# 从余额中扣除购买商品的钱
salary = salary - good_money
# 要购买的商品
good = [good_list[choice - 1][0], good_money]
# 将商品添加到已购买列表
shopping_list.append(good)
# 打印刚购买的商品,显示剩余金额
print('商品{}已成功添加到购物车,当前余额:{}元'.format(good_name, salary))
else:
print('余额不足:{}'.format(salary))
else:
print('选择有误,请重新选择!')
elif choice.upper() == 'Q':
break
else:
print('选择有误,请重新选择!')
print('已购买以下商品'.center(20, '-'))
for good in shopping_list:
print('{} {}'.format(good[0], good[1]))
print('您的余额为:{}元'.format(salary))
print('欢迎下次光临!')
元组 |
1、元组的定义
* 元组的定义和列表类似,元组使用(),列表使用[]
* 元组的特点:
1.元组是有序的,支持索引取值
2.元素可重复
3.不可变
注意:但()中只有一个值是,需要在元素的后面加一个,才表示元组
代码如下:
t1 = ()
print(type(t1)) # <class 'tuple'>
t1 = ('aa')
print(type(t1)) # <class 'str'>
t1 = ('aa',)
print(type(t1)) # <class 'tuple'>
2、根据索引和切片访问元组(跟list一样)
tuple4 = (1, 2, 3, 4, 5, 6)
print(tuple4[1]) # 2
print(tuple4[1:]) # (2,3,4,5,6)
print(len(tuple4)) # 6
3、查找元素(跟list)
# in和not in
print('a' in ('a', 'b', 'c')) # True
print('a' not in ()'a', 'b', 'c') # False
# count(value) -> integer
t1 = ()'a', 'b', 'c', 'c', 'a', 'a')
print(t1.count('a')) # 3
# index(value, start=None, stop=None) -> integer 查找元素第一次出现的索引位置,找不到报错
list1 = ('a', 'b', 'c', 'c', 'a', 'a')
print(list1.index('b')) # 1
print(list1.index('c')) # 2
# print(list1.index('d')) # ValueError: 'd' is not in list
4、支持的运算符+ 、*
print((1, 2) + (3, 4)) # (1,2,3,4)
print((1, 2) * 2) # (1,2,1,2)
5、列表的遍历
tuple4 = (1, 2, 3, 4, 5, 6)
for i in tuple4:
print(i, end='') # 123456
字典 |
1、字典的定义
格式1:book = {'name':'老人与海', 'price':30.4, '作者':'鲁迅'}
格式2:book = dict([('name','老人与海'),('price',30.4)])
特点:
1、键可以是不同的数据类型
2、键唯一
3、键可以是数字、字符串、布尔、元组等不可变数据类型,通常使用字符串
定义空字典
1、book = {}
2、book = dict()
2、获取元素
# 查找元素
# get(key) -> value 通过key获取value值,元素不存在返回None
# book = {'name': '老人与海', 'price': 30.4, '作者': '鲁迅'}
# print(book.get('name')) # '老人与海'
# print(book.get('name1')) # None
# dict1[元素] -> value,通过key获取value值,元素不存在报错
# book = {'name': '老人与海', 'price': 30.4, '作者': '鲁迅'}
# print(book['name']) # 老人与海
# print(book['name1']) # KeyError: 'name1'
# in、not in 判断key值是否存在
# book = {'name': '老人与海', 'price': 30.4, '作者': '鲁迅'}
# print('name' in book) # True
# print('name1' in book) # False
# keys() -> dict_keys 获取所有的key
# book = {'name': '老人与海', 'price': 30.4, '作者': '鲁迅'}
# for key in book.keys():
# print(key, end=' ') # name price 作者
# values() -> dict_values 获取所有的value值
# book = {'name': '老人与海', 'price': 30.4, '作者': '鲁迅'}
# for value in book.values():
# print(value, end=' ') # 老人与海 30.4 鲁迅
# items() -> dict_items 获取所有的键值对,
# book = {'name': '老人与海', 'price': 30.4, '作者': '鲁迅'}
# for k,v in book.items():
# print(k,v)
3、新增、修改元素
# book[key],key值存在就是修改,不存在就是添加
book = {}
book['name'] = '老人与海'
print(book) # {'name': '老人与海'}
book['name'] = '孙子兵法'
print(book) # {'name': '孙子兵法'}
# setdefault() -> value key值存在,添加不成功,返回字典中key对应的value值,key值不存在就添加,返回添加的value值
book = {'age': 20}
value = book.setdefault('name', '老人与海')
print(value, book) # 老人与海 {'age': 20, 'name': '老人与海'}
value = book.setdefault('age', 30)
print(value, book) # 20 {'age': 20, 'name': '老人与海'}
book = {'age': 20, 'name': '老人与海'}
book1 = {'作者': '鲁迅', 'age': 30}
book.update(book1)
print(book) # {'age': 30, 'name': '老人与海', '作者': '鲁迅'}
4、删除元素
# 删除元素
# pop(key) -> o 根据key删除键值对,并返回删除的value值,元素不存在报错
# book = {'age': 30, 'name': '老人与海', '作者': '鲁迅'}
# value = book.pop('age')
# print(value, book) # 30 {'name': '老人与海', '作者': '鲁迅'}
# book.pop('ffff') # KeyError: 'ffff'
# popitem() -> tuple 删除最后一个键值对,并以元组的方式返回删除的键值对
# book = {'age': 30, 'name': '老人与海', '作者': '鲁迅'}
# t1 = book.popitem()
# print(t1, book) # ('作者', '鲁迅') {'age': 30, 'name': '老人与海'}
# del book[key] key不存在报错
# book = {'age': 30, 'name': '老人与海', '作者': '鲁迅'}
# del book['age']
# print(book) # {'name': '老人与海', '作者': '鲁迅'}
# del book['fsfa'] # KeyError: 'fsfa'
# del book
# clear() -> None 清空集合
# book = {'age': 30, 'name': '老人与海', '作者': '鲁迅'}
# book.clear()
# print(book) # {}
5、其他函数
# len(object) -> integer 返回容器的长度
book = {'age': 30, 'name': '老人与海', '作者': '鲁迅'}
print(len(book)) # 3
6、练习:
'''
作业三:多级菜单
三级菜单
可依次选择进入各子菜单
所需新知识点:列表、字典
'''
menu = {
'湖北省': {
'武汉市': ['江岸区', '江汉区', '乔口区', '汉阳区', '武昌区'],
'荆州市': ['沙市区', '荆州区', '公安县', '监利县'],
'黄冈市': ['黄州区', '团风县', '红安县', '罗田县']
},
'湖南省': {
'长沙市': ['芙蓉区', '天心区', '岳麓区', '开福区'],
'株洲市': ['荷塘区', '芦淞区', '石峰区', '天元区', '株洲县'],
'岳阳市': ['岳阳楼区', '云溪区', '君山区', '岳阳县']
},
'广东省': {
'广州市': ['市辖区', '东山区', '荔湾区', '越秀区', '海珠区', '天河区'],
'韶关市': ['市辖区', '武江区', '浈江区', '曲江区'],
},
'四川省': {
'成都市': ['市辖区', '锦江区', '青羊区', '金牛区', '武侯区']
}
}
menu_list = [menu]
while True:
for menu in menu_list[-1]:
print(menu)
if len(menu_list) != 1 and isinstance(menu_list[-1],dict):
choice = input('请选择(退出按q,返回按b)>>>')
elif isinstance(menu_list[-1],list):
choice = input('已是最后一层,退出按q,返回按b>>>')
else:
choice = input('请选择(退出按q)>>>')
if choice in menu_list[-1] and isinstance(menu_list[-1],dict):
menu_list.append(menu_list[-1][choice])
elif choice == 'q':
break
elif choice == 'b' and len(menu_list) != 1:
menu_list.pop()
else:
print('输入有误,请重新输入!')
集合 |
特点:集合是一个不可重复,无序的序列,里面的元素都是可哈希的(不可变数据类型)
s1 = {1, 2, 3, 4, 4}
print(s1) # {1, 2, 3, 4} 自动去重
s2 = {[1,2],3,4} # TypeError: unhashable type: 'list' 组成元素要求是可哈希的
定义格式
s1 = set({1, 2, 3, 4})
s2 = {1, 2, 3, 4}
定义一个空集合使用set(),{}代表空字典
2、添加元素
# add() --> None 一次添加一个元素
s3 = {1, 2, 3}
print(s3.add(4)) # None
print(s3) # {1, 2, 3, 4}
# update() --> None 添加一个序列,可以是字符串、列表、元素、字典、集合
s4 = {1, 2, 3}
print(s4.update({4, 5, 6})) # None
print(s4) # {1, 2, 3, 4, 5, 6}
3、删除元素
# remove(e) --> None 删除一个元素,删除元素不存在报错
s5 = {1, 2, 3, 4}
print(s5.remove(1)) # None
print(s5) # {2,3,4}
# s5.remove(6) # KeyError: 6 报错
# pop() --> value 随机删除一个元素,并且返回删除的值,集合为空时删除报错
s6 = {1, 2}
print(s6.pop()) # 1
s6.pop()
# s6.pop() # KeyError: 'pop from an empty set'
# discard() --> None 删除指定的元素,元素不存在不会报错
s7 = {1, 2}
print(s7.discard(1)) # None
s7.discard(3)
4、集合类型操作符
# in、not in
# 集合等价与不等价(==,!=)
print({1, 2, 3} == {1, 2, 3}) # True
print({1, 2, 3} == {1, 2, 4}) # False
print({1, 2, 3} != {1, 2, 3}) # False
print({1, 2, 3} != {1, 2, 4}) # True
# 子集、超级(<,<=,>,>=,issubset(),issuperset)
print({1, 2, 3} < {1, 2, 3, 4}) # True
print({1, 2, 3} < {1, 2, 3}) # Flase
print({1, 2, 3, 4} > {1, 2, 3}) # True
print({1, 2, 3} > {1, 2, 3}) # Flase
print({1, 2, 3}.issubset({1, 2, 3, 4})) # True
print({1, 2, 3}.issubset({1, 2, 3})) # True
print({1, 2, 3, 4}.issuperset({1, 2, 3})) # True
# 交集(intersection()、&)、并集()、差集()、对称差集()
s1 = {1, 2, 3, 4, 5}
s2 = {4, 5, 6, 7, 8}
print(s1 & s2) # {4,5}
print(s1.intersection(s2)) # {4,5}
print(s1 | s2) # {1, 2, 3, 4, 5, 6, 7, 8}
print(s1.union(s2)) # {1, 2, 3, 4, 5, 6, 7, 8}
print(s1 - s2) # {1,2,3}
print(s1.difference(s2)) # {1,2,3}
print(s1 ^ s2) # {1, 2, 3, 6, 7, 8}
print(s1.symmetric_difference(s2)) # {1, 2, 3, 6, 7, 8}
字符串 |
1、字符串的基本操作
# 1 * 重复输出字符串
print('hello'*2)
# 2 [] ,[:] 通过索引获取字符串中字符,这里和列表的切片操作是相同的,具体内容见列表
print('helloworld'[2:])
# 3 in 成员运算符 - 如果字符串中包含给定的字符返回 True
print('el' in 'hello')
# 4 % 格式字符串
print('alex is a good teacher')
print('%s is a good teacher'%'alex')
# 5 + 字符串拼接
a='123'
b='abc'
c='789'
d1=a+b+c
print(d1)
# +效率低,该用join
d2=''.join([a,b,c])
print(d2)
2、字符串的内置函数
# len(object) -> integer 获取容器的长度
print(len('abcde')) # 5
# find(sub, start=None, end=None) -> int 检测 str 是否包含在字符串中,如果指定范围 beg 和 end ,则检查是否包含在指定范围内,如果包含返回开始的索引值,否则返回-1
print('hello world'.find('l')) # 2
print('hello world'.find('ddd')) # -1
# rfind(sub, start=None, end=None) -> int 返回字符串最后一次出现的位置,如果没有匹配项则返回-1
# index(sub, start=None, end=None) -> int 跟find()方法一样,只不过如果str不在字符串中会报一个异常
# rindex(sub, start=None, end=None) -> int 跟rfind()方法一样,只不过如果str不在字符串中会报一个异常
# startswith() -> bool 检查字符串是否是以指定子字符串 substr 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查
print('hello world'.startswith('h')) # True
# endswith() -> bool 检查字符串是否以 suffix 结束,如果 beg 或者 end 指定则检查指定的范围内是否以 suffix 结束,如果是,返回 True,否则返回 False
print('hello world'.endswith('d')) # True
# isalpha() -> bool 如果字符串至少有一个字符并且所有字符都是字母或中文字则返回 True, 否则返回 False
print('aadfdf'.isalpha()) # True
print('fsda22'.isalpha()) # False
# isdigit() -> bool 如果字符串只包含数字则返回 True 否则返回 False
print('1234'.isdigit()) # True
print('2444.3'.isdigit()) # False
# isalnum() -> bool 如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False
print('fasdf333'.isalnum()) # True
# isspace() -> bool 如果字符串中只包含空白,则返回 True,否则返回 False
print(' '.isspace()) # True
# count() -> int
print('hello world'.count('l')) # 3
# istitle() -> bool 如果字符串是标题化的(见 title())则返回 True,否则返回 False
print('Hello World'.istitle()) # True
print('Hello world'.istitle()) # False
# replace(old, new, count=None)) -> str 把 将字符串中的 old 替换成 new,如果 max 指定,则替换不超过 max 次
print('hello world'.replace('l', 'u')) # heuuo worud
# split(sep=None, maxsplit=-1) -> list 以 str 为分隔符截取字符串,如果 num 有指定值,则仅截取 num+1 个子字符串
print('hello world'.split('-')) # ['hello world']
# rsplit(sep=None, maxsplit=-1) -> list 用法和split基本一致,只不过是从右往左分隔
# spiltlines(keepends=None) -> list 按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符
mystr = 'hello \nworld'
print(mystr.splitlines()) # ['hello ', 'world']
# rpartition(sep)、partition(sep) -> () 把mystr以str分割成三部分,str前,str和str后,三部分组成一个元组
mystr = '今天天气好晴朗,处处好风光呀好风光'
print(mystr.rpartition('好')) # ('今天天气好晴朗,处处好风光呀', '好', '风光')
# capitalize() -> str 将第一个单词的首字母大写
print('hello world'.capitalize()) # Hello world
# title() -> str 将每个单词的首字母大写
print('hello world') # Hello World
# lower() -> str 转小写
# upper() -> str 转大写
# swapcase() -> str 大写转小写,小写转大写
# ljust(width,fillchar=None) -> str 返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格
# rjust(width,fillchar=None) -> str 返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度 width 的新字符串
# center(width,fillchar=None) -> str 返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格
# strip() -> str 截掉字符串两边的空格或指定字符
name = ' hello '
print(name.strip()) # hello
# lstrip() -> str 截掉字符串左边的空格或指定字符
# rtrip() -> str 截掉字符串右边的空格或指定字符
# join(iterable) -> str, 以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串
print('_'.join(['hello', 'world'])) # hello_world
print('_'.join(('hello', 'world'))) # hello_world
print('_'.join('abc')) # a_b_c
print('_'.join({'name': 'zz', 'age': 3})) # name_age
3、字符串格式化format
1、简单字段名
简单字段名的3中写法
a:省略字段名:{}
b:使用非负十进制整数{0}
c:变量名{name}
2、使用省略字段名的方式
替换字段形式{}
注意:大括号的个数可以少于参数的个数,反之亦然
name = '张三'
age = 18
print('我叫{},我的年龄是{}'.format(name, age)) #我叫张三,我的年龄是18
print('我叫{},我的年龄是{},他叫{}'.format(name, age)) #IndexError: tuple index out of range,大括号的个数大于了参数的个数
print('我叫{},我的年龄是{}'.format(name, age,40)) #我叫张三,我的年龄是18
3、数字字段名
.数字必须是大于0的整数
.带数字的替换字段可以重复使用
.数字形式的简单字段名相当于把 format 中的所有位置参数整体当作一个元组,通过字段名中的数字进行取值。即 {0} 等价于 tuple[0 ],所以大括号内的数字不能越界
name = '张三'
age = 18
print('他叫{0},今年{1}'.format(name, age)) # 他叫张三,今年18
print('他叫{0},今年{1},我今年也{1}'.format(name, age)) # 他叫张三,今年18,我今年也18
# print('他叫{0},今年{1},我今年也{2}'.format(name, age)) # tuple index out of range
print('他叫{},今年{1},我今年也{0}'.format(name, age)) # 报错 {} 和 {0} 不能同时使用
4、变量字段名
.使用变量名形式的简单字段名传递参数关键字参数
print('我叫{name},今年{age}岁'.format(name='李四', age=20)) # 我叫李四,今年20岁
print('我叫{name},今年{age}岁'.format(age=20, name='李四')) # 关键字参数位置可以随意调换
编码与解码 |
1、编码介绍
1.在python2默认编码是ASCII, python3里默认是unicode
2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-16就是现在最常用的unicode版本, 不过在文件里存的还是utf-8,因为utf8省空间
3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string
4、在utf-8下一个中文占3个字节,gbk下一个中文占2个字节
2、python2下的编码与解码
# encoding:utf-8
str = '中国'
print(str)
# 将utf-8转换成unicode编码,解码时需要指定的内容的编码格式(小-> 大 叫做解码)
str = str.decode('utf-8')
print(str) # (<type 'unicode'>, u'\u4e2d\u56fd')
# 将unicode转换成gbk (大 -> 小 叫做编码)
str = str.encode('gbk')
print(str) # (<type 'str'>, '\xd6\xd0\xb9\xfa')
# 将gbk解码成unicode (小 -> 叫做解码)
str = str.decode('gbk') # (<type 'unicode'>, u'\u4e2d\u56fd')
print(str)
# 将unicode 编码转换成 utf-8
str = str.encode('utf-8')
print(str) # (<type 'str'>, '\xe4\xb8\xad\xe5\x9b\xbd')
3、python3下的编码与解码
#__author: 杜幼志
#date: 2023-03-26
'''
py3下默认编码为unicode
encode:编码,将字符串转换成bytes
decode:解码,将bytes转换成字符串
'''
str = '中国'
# 将unicode转换成gbk
unicode_to_gbk = str.encode('gbk')
print(unicode_to_gbk) # b'\xd6\xd0\xb9\xfa'
# 将gbk转换成unicode
gbk_to_unicode = unicode_to_gbk.decode('gbk')
print(gbk_to_unicode) # 中国
# 将unicode转换成utf-8
unicode_to_utf8 = gbk_to_unicode.encode('utf-8')
print(unicode_to_utf8) # b'\xe4\xb8\xad\xe5\x9b\xbd'
# 将utf-8转换成unicode
utf8_to_unicode = unicode_to_utf8.decode('utf-8')
print(utf8_to_unicode) # 中国