英文:
How can I use .format with a list?
问题
"我仍然是Python的初学者,只是为了练习而编写了一些简单的代码。我定义了一个包含一些姓名的列表,以便稍后打印出来,但我无法以我想要的方式实现它。
我做得有点像这样:
names = ['John', 'Karl', 'Anne', 'Beth']
print("Those kids' names are {}.".format(names))
它返回"Those kids' names are ['John', 'Karl', 'Anne', 'Beth']."。
我希望它显示时不带括号([])和引号(''),像这样:"Those kids' names are John, Karl, Anne, Beth."。
有办法可以做到吗?"
英文:
I'm still a beginner at Python, and was doing some simple code just to exercise. I defined a list with some names, so I could print it afterwards, but I can't really do it the way I want.
I did it kind of like this:
names = ['John', 'Karl', 'Anne', 'Beth']
print("Those kids' names are {}.".format(names))
It returns "Those kids' names are ['John', 'Karl', 'Anne', 'Beth']."
I wanted it to be displayed without the brackets ([]) and the quotes (''), like this:
"Those kids' names are John, Karl, Anne, Beth."
Is there a way to do that?
答案1
得分: 3
使用str.join
来使用给定的分隔符连接一个字符串可迭代对象。
names = ['John', 'Karl', 'Anne', 'Beth']
print(f"Those kids' names are {', '.join(names)}.")
英文:
Use str.join
to join an iterable of strings with a given separator.
names = ['John', 'Karl', 'Anne', 'Beth']
print(f"Those kids' names are {', '.join(names)}.")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论