如何使用 .format 与列表?

huangapple go评论78阅读模式
英文:

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)}.")

huangapple
  • 本文由 发表于 2023年6月13日 04:06:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76459977.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定