python 字符串和字节、字典、列表、json、类等的相互转换

1、字符串string和字节对象bytes的转换

  • bytes转string

  (1)r.read()       -->type:bytes

  (2)r.read().decode()  --->type:string

  (3)s = str(bytes, encoding='utf-8')     将字节对象转换为字符串

  • string转bytes

  (1)r.encode()     --->type:bytes

  (2)s = bytes(string, encoding='utf-8')   将字符串转换为字节对象


with open('news.txt', mode='rb+')as f:
    news = f.read()        # bytes
    news = news.decode()     # str
    news = str(news, encoding='utf-8')     # str
    print(news)

运用:读取文本/HTML文本、图片、视频、字节流

 

2、字符串和字典

  • dict转string

  (1)json.dumps(dict)  --->type:string

    dumps转换的是Unicode字符,显示中文字符添加参数: ensure_ascii=False

  (2)字典强制转换为字符串

    str(dict)

  • string转dict

  (1)json.loads(string)  --->type:dict

    str格式为单引号包括内容,字典key和value用双引号'{"a":"1"}'

  (2)字典转换为字符串第二种方法

    eval(str)

import json

dict1 = {'a': 1, 'b': '2', 'c': ''}
str2 = '{"a": 1, "b": "2", "c": "三"}'
# str1会报错json.decoder.JSONDecodeError:
# Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
# str1 = "{'a': 1, 'b': '2', 'c': '三'}"

# 字典转换为字符串
result = json.dumps(dict1, ensure_ascii=False)
print(result)
# 强制转换
result = str(dict1)
# 字符串转字典
result = json.loads(str2)
# 或者
result = eval(str2)
print(result)

 

3、字符串和列表

  • list转string

  (1)' '.join()方法  '\n'.join(),列表中的每个值都是字符串,如list1的索引3的值为:518,此时会报错

  (2)遍历    for i in list:print(i)

  (3)遍历②   [str(i) for i in list]

  (4)强制转换  str(list)


list1 = ['Mike', '徐清风', '666', 518, '$_$']
list2 = ['Mike', '徐清风', '666', '$_$']
str1 = '["Mike", "徐清风", "666", 518, "$_$"]'
str2 = '将字符串每个值转换成列表'

#
一 join方法 result = ''.join(list2) # 二 遍历 循环打印索引0-len(list1)对应的值 for li in list1: print(li) # 三,没有[]输出是内存地址 print([str(li) for li in list1]) # result = str(list1)

 

  • string转list

  (1)eval函数  eval(str)

  (2)list,将字符串每个值都转换成列表中的值  list(str)

  (3)字符串分割方法  str.split('字符串分割线')

#
result = eval(str1)
#
result = list(str2)
#
result = str1.split(',')
result = str2.split('')

 

4、字典和列表

  • 列表转字典

  (1)dict(list1,list2)

  (2)dict(list)

  • 字典转列表

  (1)list(dict.keys())

  (2)list(dict.values())

dict1 = {'a': 1, 'b': '2', 'c': ''}
list1 = ['Mike', '徐清风', '666', '$_$', 'ha']
list2 = ['88', 'beautiful', '真棒', 'rich']
list3 = [['one', '1'], ['two', '2'], ['three', 3]]

"""列表转字典"""
# 两个列表转换成字典,按索引值对照,超出范围的不配对不会报错
result = dict(zip(list1, list2))
嵌套列表转换成字典,key=value若无匹配会报错
# result = dict(list3)


"""字典转列表"""
result = list(dict1.keys())
result = list(dict1.values())
print(result)

 

5、json和字符串

 

6、类和字符串

 1 # coding:utf-8
 2 # 定义一个Student类
 3 import json
 4 
 5 
 6 class Student(object):
 7     def __init__(self, name, age, score):
 8         self.name = name
 9         self.age = age
10         self.score = score
11 
12 
13 # 实例化这个对象
14 s = Student('hello', 20, 80)
15 
16 
17 # 定义一个转换函数,将Student类换成json可以接受的类型
18 def student2dict(std):
19     return {
20         'name': std.name,
21         'age': std.age,
22         'score': std.score
23     }
24 
25 
26 # 这样就可以将类对象转换成json了,这里利用json的default属性来调用student2dict函数
27 print(json.dumps(s, default=student2dict))

 

posted @ 2021-06-01 18:15  SpriteGirl  阅读(1221)  评论(0)    收藏  举报