Python 如何在一行而不是单独打印列表的值
例如,而不是类似于: 我的朋友是凯特 我的朋友是马特 我想打印出: 我的朋友是凯特,马特Python 如何在一行而不是单独打印列表的值,python,python-3.x,list,Python,Python 3.x,List,例如,而不是类似于: 我的朋友是凯特 我的朋友是马特 我想打印出: 我的朋友是凯特,马特 使用join生成要打印的整个字符串,然后调用print一次: print("My friends are " + ", ".join(myFriends)) 使用join生成要打印的整个字符串,然后调用print一次: print("My friends are " + ", ".join(myFriends)) 这是一种方式。您可以将str.format与,”结合使用。加入以所需格式打印 myFrie
使用
join
生成要打印的整个字符串,然后调用print
一次:
print("My friends are " + ", ".join(myFriends))
使用
join
生成要打印的整个字符串,然后调用print
一次:
print("My friends are " + ", ".join(myFriends))
这是一种方式。您可以将
str.format
与,”结合使用。加入以所需格式打印
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()
这是一种方式。您可以将str.format
与,”结合使用。加入以所需格式打印
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()
您还可以执行以下操作
for friend in myFriends:
print(friend, end=', ')
这应该给你这个输出
Kate,Matt,您也可以执行以下操作
for friend in myFriends:
print(friend, end=', ')
这应该给你这个输出
凯特,马特,嗯,是的,我们可以。但是它应该给出这个输出吗?是的,我们可以。但是它是否应该提供此输出?您的代码不会产生任何一个输出。您的代码不会产生任何一个输出。{0}
是格式字符串的最后一部分。与简单的+
相比,它是否有任何优势,除了在需求发生变化时更容易更改格式之外?(我认为这是一个非常合理的理由。只要OP想要添加一个简单的句号,格式
解决方案就会变得更加简洁)一些(,)人,包括我在内,认为str.format
更具可读性。这提供了所有选项。{0}
是格式字符串的最后一部分。与简单的+
相比,它是否有任何优势,除了在需求发生变化时更容易更改格式之外?(我认为这是一个非常合理的理由。只要OP想要添加一个简单的句号,格式
解决方案就会变得更加简洁)一些(,)人,包括我在内,认为str.format
更具可读性。这提供了所有的选择。