gpt4 book ai didi

python - 如何在 python 中将字符串或字典分成多行?

转载 作者:太空宇宙 更新时间:2023-11-04 03:22:51 25 4
gpt4 key购买 nike

我确实做了一本字典:

{
"PerezHilton": {
"name": "Perez Hilton",
"following": [
"tomCruise",
"katieH",
"NicoleKidman"
],
"location": "Hollywood, California",
"web": "http://www.PerezH...",
"bio": [
"Perez Hilton is the creator and writer of one of the most famous websites",
"in the world. And he also loves music - a lot!"
]
},
"tomCruise": {
"name": "Tom Cruise",
"following": [
"katieH",
"NicoleKidman"
],
"location": "Los Angeles, CA",
"web": "http://www.tomcruise.com",
"bio": [
"Official TomCruise.com crew tweets. We love you guys!",
"Visit us at Facebook!"
]
}
}

我希望它返回一个字符串,所以我向它添加了 str() 。但我不知道如何像线条一样打破它。我需要的是:

----------
PerezHilton
name: Perez Hilton
location: Hollywood, California
website: http://www.PerezH...
bio:
Perez Hilton is the creator and writer of one of the most famous websites
in the world. And he also loves music - a lot!
following: ['tomCruise', 'katieH', 'NicoleKidman']
----------
tomCruise
name: Tom Cruise
location: Los Angeles, CA
website: http://www.tomcruise.com
bio:
Official TomCruise.com crew tweets. We love you guys!
Visit us at Facebook!
following: ['katieH', 'NicoleKidman']
----------

我应该把它改成字符串然后再打断吗?或者将它们从 dict 中分离出来并将其作为一个字符串?顺便说一句,我用的是 python 3

最佳答案

试试这个:

_dict = {
"PerezHilton": {
"name": "Perez Hilton",
"following": [
"tomCruise",
"katieH",
"NicoleKidman"
],
"location": "Hollywood, California",
"web": "http://www.PerezH...",
"bio": [
"Perez Hilton is the creator and writer of one of the most famous websites",
"in the world. And he also loves music - a lot!"
]
},
"tomCruise": {
"name": "Tom Cruise",
"following": [
"katieH",
"NicoleKidman"
],
"location": "Los Angeles, CA",
"web": "http://www.tomcruise.com",
"bio": [
"Official TomCruise.com crew tweets. We love you guys!",
"Visit us at Facebook!"
]
}
}

def str_generator(key, value):
if isinstance(value, str):
return key +': ' + value
elif key == 'bio':
return key + ':\n' + '\n'.join(value)
else:
return key + ': ' + str(value)


a = ""


for key, value in _dict.items():
a += ('----------\n' + key + '\n')
for _key, _value in value.items():
a += (''.join(str_generator(_key, _value)) + '\n')


print(a)

输出:

----------
tomCruise
location: Los Angeles, CA
following: ['katieH', 'NicoleKidman']
name: Tom Cruise
bio:
Official TomCruise.com crew tweets. We love you guys!
Visit us at Facebook!
web: http://www.tomcruise.com
----------
PerezHilton
location: Hollywood, California
following: ['tomCruise', 'katieH', 'NicoleKidman']
name: Perez Hilton
bio:
Perez Hilton is the creator and writer of one of the most famous websites
in the world. And he also loves music - a lot!
web: http://www.PerezH...

关于python - 如何在 python 中将字符串或字典分成多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34125613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com