【问题标题】:how to use the sep parameter in the print function correctly如何正确使用打印函数中的sep参数
【发布时间】:2020-01-15 11:57:03
【问题描述】:

我一直在尝试在 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 将不同的条目与列表分开。

【问题讨论】:

  • 打印输出是什么?

标签: python function printing parameters separator


【解决方案1】:

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

更好的是,只需这样做:

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

【讨论】:

  • 这对我来说似乎是一个优雅的解决方案@Alex Hall,谢谢。我只是在逗号后添加了一个空格字符。您在这里使用的概念的名称是什么?不知何故,它看起来类似于列表推导,但我认为您不会那样称呼它,对吗?
  • 我查看了您的建议并将其称为概念:使用分隔符将列表连接成字符串。 v.title() for v in value 返回一个列表。然后将 v 的值连接起来,用 ', ' 将它们分隔开来。
【解决方案2】:

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

例如

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 2012-09-02
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多