python如何把字典转换成字符串

41次阅读
没有评论

共计 450 个字符,预计需要花费 2 分钟才能阅读完成。

要把字典转换为字符串,可以使用 json 库中的 dumps() 函数。下面是使用 json 库将字典转换为字符串的示例代码:

import json

dict_obj = {'name': 'Alice', 'age': 25}

# 将字典转换为字符串 
json_str = json.dumps(dict_obj)

print(json_str)

输出结果:

{"name": "Alice", "age": 25}

另外,如果想要将字典转换为格式化的字符串,可以使用 dumps() 函数的 indent 参数。例如:

import json

dict_obj = {'name': 'Alice', 'age': 25}

# 将字典转换为格式化的字符串 
json_str = json.dumps(dict_obj, indent=4)

print(json_str)

输出结果:

{
    "name": "Alice",
    "age": 25
}

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-02-05发表,共计450字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)