如何正确使用打印函数中的sep参数

how to use the sep parameter in the print function correctly

我一直在尝试在 python 中构建词典。请考虑以下代码:

brad_pitt = {
'name': ['brad pitt'],
'profession': ['actor'],
'birthday': ['18.12.1963'],
'sign': ['sagittarius'],
'birthplace': ['shawnee / oklahoma (usa)'],
'nationality': ['usa'],
'height': ['182 cm'],
'weight': ['76 kg'], 
'marital status': ['married'],
'sex': ['male'],
'ex-partner': ['gwyneth paltrow', 'jennifer aniston', 'angelina jolie'],
'eye color': ['blue'],
}

julia_roberts = {
'name': ['julia roberts'],
'profession': ['actor'],
'birthday': ['28.10.1967'],
'sign': ['scorpion'],
'birthplace': ['atlanta / georgia (usa)'],
'nationality': ['usa'],
'height': ['174 cm'],
'weight': ['57 kg'], 
'marital status': ['married'],
'sex': ['female'],
'ex-partner': ['liam neeson'],
'eye color': ['brown'],
}

george_clooney = {
'name': ['george clooney'],
'profession': ['actor'],
'birthday': ['06.05.1961'],
'sign': ['taurus'],
'birthplace': ['lexington / kentucky (usa)'],
'nationality': ['usa'],
'height': ['180 cm'],
'weight': ['74 kg'], 
'marital status': ['married'],
'sex': ['male'],
'ex-partner': ['naomi campbell', 'elle macpherson', 'renée zellweger', 'amal clooney'],
'eye color': ['brown'],
}

people = [brad_pitt, julia_roberts, george_clooney]

for person in people:
    for key, value in person.items():
        if len(value) > 1:
            print(f"{key.title()}: ", end="")
            for partner in value:
                print(f"{partner}".title(), sep=',', end="")
            print()
        else:
            print(f"{key.title()}: {value[0].title()}")
    print()

我希望前伙伴之间用逗号分隔...

我在打印语句中没有看到错误。

我使用了可选参数 sep 来分隔列表中的不同条目。

sep 用于将多个参数传递给 print。而是设置 end=",".

更好的是,只需这样做:

for key, value in person.items():
    print(f"{key.title()}: {','.join(v.title() for v in value)}")

sep 用于传递要分隔的字符串列表,您似乎在 for 循环中一个一个地传递字符串。我要么删除 for 循环并只打印 value,要么将其更改为 end=','

例如

for partner in value:
    print(f"{partner}".title(), end=", ")

print(f"{value}".title(), sep=', ' , end="")