以逗号分隔的 1 行打印输出
我有 1 个列表:
mylist=[John, Stefan, Bjarke, Eric, Weirdo]
我想使用 for 循环将整个内容打印在一行中,并用逗号分隔,例如:
for x in mylist:
print x
我该怎么做?
I have 1 list:
mylist=[John, Stefan, Bjarke, Eric, Weirdo]
I want to print the whole thing in one line separated by commas using a for loop, like:
for x in mylist:
print x
How do I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
或者如果 John Stefan 等还不是字符串:
or if John Stefan etc are not already strings:
其他答案更聪明,也更“Pythonic”。但如果你确实需要一个循环:
但这会在下一次打印时在打印之前留出一个空格。如果使用
sys.stdout
,打印将在上次打印后直接开始:sys.stdout.write
不添加空格,并且'\r
将使打印从行首开始。这对于刷新命令行中的显示可能很有用。所以,回答你的问题:
但是这一行将以逗号结尾,而
str.join
函数则不是这种情况。Other answers are smarter, and more 'Pythonic'. But if you really need a loop:
But this will let one space at next printing before the print. If you use
sys.stdout
, the printing will start directly after previous printing:sys.stdout.write
is not adding spaces, and'\r
will make printing to start back at beginning of line. This may be useful for refreshed display in command line.So, to answer to your question:
But this line will end with a coma, which is not the case with
str.join
function.尝试这样做:
不需要 for 循环。
Try doing this:
A for loop is not needed.
只是为了好玩,有 Perl 风格的 hax0ring 方式:
;)
Just for fun, there's the Perl-esque hax0ring way:
;)