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

2024-09-27 07:30:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我确实做了一本字典:

{
    "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()。 但我不知道怎么像线一样打破它。 我需要的是:

^{pr2}$

我应该把它换成绳子然后再把它弄断吗?或者把它们从dict中分离出来当作一个字符串? 顺便说一句,我用的是python3


Tags: ofthenamecomwebhttpwwwlocation
1条回答
网友
1楼 · 发布于 2024-09-27 07:30:41

试试这个:

_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)

输出:

^{pr2}$

相关问题 更多 >

    热门问题