【问题标题】:How do I print the values of a list in one line rather than separately如何在一行中而不是单独打印列表的值
【发布时间】:2018-04-02 00:44:31
【问题描述】:

例如,而不是类似的东西:

我的朋友是凯特

我的朋友是马特

我要打印出来:

我的朋友是凯特,马特

myFriends = []

def add_new_friend():
    while True:
        newFriend = input("Add your new friend (Enter blank to quit):")
        if newFriend == "":
            break
        elif newFriend == "check":
            check_friends()
        else:
            myFriends.append(newFriend)
            for friend in range(len(myFriends)):
                print(myFriends[friend])

【问题讨论】:

  • 您的代码不会产生这些输出中的任何一个。

标签: python python-3.x list


【解决方案1】:

使用join 构建要打印的整个字符串,然后调用print 一次:

print("My friends are " + ", ".join(myFriends))

【讨论】:

    【解决方案2】:

    这是一种方式。您可以使用str.format 结合', '.join 以您需要的格式打印。

    myFriends = []
    
    def add_new_friend():
        while True:
            newFriend = input("Add your new friend (Enter blank to quit):")
            if newFriend == "":
                break
            elif newFriend == "check":
                check_friends()
            else:
                myFriends.append(newFriend)
                print('My friends are: {0}'.format(', '.join(myFriends)))
    
    add_new_friend()
    

    【讨论】:

    • {0} 是格式字符串的最后一部分。与简单的+ 相比,它是否有任何优势,除了如果需求发生变化更容易更改格式? (这将是一个完全正当的理由,我明白了。只要 OP 想要附加一个简单的句点,format 解决方案就会变得更加简洁)
    • 包括我在内的一些(12)认为str.format 更具可读性。这个good answer 提供了所有选项。
    【解决方案3】:

    您还可以执行以下操作

    for friend in myFriends:
      print(friend, end=', ')
    

    这应该会给你这个输出......

    凯特,马特,

    【讨论】:

    • 嗯,是的,我们可以。但是……应该给出这个输出吗?
    猜你喜欢
    • 2016-12-16
    • 2018-12-22
    • 1970-01-01
    • 2023-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    • 2019-09-01
    相关资源
    最近更新 更多