python字典怎么转化为字符串

50次阅读
没有评论

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

要将字典转换为字符串,可以使用字典的 str()方法或者使用 json 模块的 dumps()函数。

方法一:使用 str()方法

my_dict = {'name': 'John', 'age': 28, 'city': 'New York'}
my_str = str(my_dict)
print(my_str)

输出:

{'name': 'John', 'age': 28, 'city': 'New York'}

方法二:使用 json 模块的 dumps()函数

import json

my_dict = {'name': 'John', 'age': 28, 'city': 'New York'}
my_str = json.dumps(my_dict)
print(my_str)

输出:

{"name": "John", "age": 28, "city": "New York"}

注意:使用 json.dumps()函数将字典转换为字符串时,会将字典中的键名用双引号括起来。如果想要保持原字典的格式,可以使用 json.dumps()函数的 ensure_ascii=False 参数:

import json

my_dict = {'name': 'John', 'age': 28, 'city': 'New York'}
my_str = json.dumps(my_dict, ensure_ascii=False)
print(my_str)

输出:

{"name": "John", "age": 28, "city": "New York"}

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

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