首页 > 编程语言 > 详细

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

时间:2021-06-01 19:15:23      阅读:25      评论:0      收藏:0      [点我收藏+]

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)

 

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

原文:https://www.cnblogs.com/spritegirl/p/14838349.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!