使用分隔符打印列表中的所有项目
给定一个Python列表,在最后一个元素之后使用逗号分隔符/分隔符打印它的首选方法是什么,并且没有中间空格,并且末尾没有尾随逗号:
我尝试过:
a = [1, 2, 3]
for element in a:
print str(element) + ",", # old Python 2 syntax
output
1,2,3,
desired
1,2,3
Given a Python list, what is the preferred way to print it with comma delimiter/separator, and no intervening spaces, and no trailing comma at the end, after the last element:
I tried:
a = [1, 2, 3]
for element in a:
print str(element) + ",", # old Python 2 syntax
output
1,2,3,
desired
1,2,3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
这非常简单:
在 Python 中打印列表(4 种不同的方式)< /a>
It's very easy:
Print lists in Python (4 Different Ways)
其他答案中建议的
','.join
是典型的 Python 解决方案;到目前为止我在任何答案中都没有看到的正常方法被称为生成器表达式或 genexp。
如果您更喜欢循环(或者需要一个循环用于其他目的,例如,如果您要做的不仅仅是在每个项目上打印),当然还有很好的替代方案:
这是第一次切换(适用于任何可迭代的对象) a,无论是列表还是其他),因此它将逗号放在每个项目之前,但第一个除外。最后一次切换稍微不太优雅,它仅适用于具有 len() 的迭代(不适用于完全通用的迭代):
此示例还利用最后一次切换来终止打印最后一项时的行。
enumerate 内置函数通常很有用,而且很好值得牢记!
A
','.join
as suggested in other answers is the typical Python solution; the normal approach, which peculiarly I don't see in any of the answers so far, isknown as a generator expression or genexp.
If you prefer a loop (or need one for other purposes, if you're doing more than just printing on each item, for example), there are of course also excellent alternatives:
this is a first-time switch (works for any iterable a, whether a list or otherwise) so it places the comma before each item but the first. A last-time switch is slightly less elegant and it work only for iterables which have a
len()
(not for completely general ones):this example also takes advantage of the last-time switch to terminate the line when it's printing the very last item.
The enumerate built-in function is very often useful, and well worth keeping in mind!
有两个选项,
您可以使用直接打印答案
打印(*a, sep=',')
这将使用分隔符作为“,”,您将得到答案为 ,
另一个选项是 ,
这将迭代列表并打印 (a) 并将输出打印为
There are two options ,
You can directly print the answer using
print(*a, sep=',')
this will use separator as "," you will get the answer as ,
and another option is ,
this will iterate the list and print the (a) and print the output as
这就是
join
的用途。That's what
join
is for.print (stringTokenizer(u"привет парни! я вам стихами, может быть, еще отвечу",", !"))
print (stringTokenizer(u"привет парни! я вам стихами, может быть, еще отвечу",", !"))