您的位置:首页 > 娱乐 > 八卦 > python的字典、列表以及json和字典转换、字符操作

python的字典、列表以及json和字典转换、字符操作

2025/7/13 11:05:12 来源:https://blog.csdn.net/ZENGZISUZI/article/details/140003474  浏览:    关键词:python的字典、列表以及json和字典转换、字符操作

1.python获取字典的key
2.sort()用法:对列表原列表进行从小到大的排序。
3.json和字典相互转换(json.dump、json.dumps、json.loads、json.load)方法使用
4.python的字符操作(strip()、split()、join()、replace())

# 1.python获取字典的key
my_dict = {'name': '小明', 'age': 18}
keys = my_dict.keys()
print(keys)  # dict_keys(['name', 'age'])
keys = list(my_dict.keys())
print(keys)  # ['name', 'age']# 2.sort()用法:对列表原列表进行从小到大的排序。
a = [1, 2, 5, 3, 8, 0]
print(a.sort())  # None
x = [8, 9, 0, 7, 4, 5, 1, 2, 3, 6]
x.sort()
print(x)  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]# 3.json和字典相互转换(json.dump、json.dumps、json.loads、json.load)方法使用
# dump dumps都是讲python 对象转换为json字符串
# load loads都是把json字符串转换为python对象(通常为字典类型dict)
# 除了上面的功能
# dump 和load分别还对应了写入文件与读取文件的功能(配合with open)
# 而dumps loads没有
import jsondata = {"name": "john","age": "18"
}
print(type(data))  # <class 'dict'>
# dumps转换dict类型为str类型
json_str = json.dumps(data)
print(json_str)  # {"name": "john", "age": "18"}
print(type(json_str))  # <class 'str'># dump转换格式并写入文件
with open('dump_data.json', 'w', encoding='UTF-8') as f:json.dump(data, f)  # 输出一个json文件# loads转换str类型为dict类型
data = json.loads(json_str)
print(type(data))  # <class 'dict'># load读取文件并转换格式
with open('dump_data.json', 'r') as f:data = json.load(f)print(data)  # {"name": "john", "age": "18"}print(type(data))  # <class 'dict'># 4.python的字符操作(strip()、split()、join()、replace())
# strip():头尾包含有指定字符序列中的字符就删除
# split():通过指定分隔符对字符串进行切片,该方法将字符串分割成子字符串并返回一个由这些子字符串组成的列表。
# join():将序列中的元素以指定的字符连接生成一个新的字符串。
# replace():把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次
str = "*****this is **string** example....wow!!!*****"
print(str.strip('*'))  # this is **string** example....wow!!!
str = "123abcrunoob321"
print(str.strip('12'))  # 3abcrunoob3str = "this is string example....wow!!!"
# 默认以空格为分隔符
print(str.split())  # ['this', 'is', 'string', 'example....wow!!!']
# 以 i 为分隔符,第二个参数为 1,返回两个参数列表
print(str.split('i', 1))  # ['th', 's is string example....wow!!!']
# 以 w 为分隔符
print(str.split('w'))  # ['this is string example....', 'o', '!!!']seq = ("a", "d", "d", "s", "u", "n")  # 字符串序列
print("-".join(seq))  # a-d-d-s-u-n
print("".join(seq))  # addsunstr = "xxxxxxxxxxxxxxx"
print("急停按钮:", str) # 急停按钮: xxxxxxxxxxxxxxx
print("急停新按钮:", str.replace("xxxxxxxxxxxxxxx", "yy")) # 急停新按钮: yystr = "this is string example....wow!!!"
print(str.replace("is", "was", 3)) # thwas was string example....wow!!!

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com