简体   繁体   English

如何在循环中打印值之间的空格?

[英]How to print spaces between values in loop?

I am a bit new in Python so, I want to know How to put spaces between values in a print() statement for example:我对 Python 有点陌生,所以我想知道如何在 print() 语句中的值之间放置空格,例如:

for i in range(5):
    print(i, sep='', end='')

prints印刷

012345

I would like it to print我想打印

0 1 2 3 4 5

While others have given an answer, a good option here is to avoid using a loop and multiple print statements at all, and simply use the * operator to unpack your iterable into the arguments for print:虽然其他人已经给出了答案,但这里的一个好选择是完全避免使用循环和多个打印语句,只需使用*运算符将您的可迭代对象解压缩到打印参数中:

>>> print(*range(5))
0 1 2 3 4

As print() adds spaces between arguments automatically, this makes for a really concise and readable way to do this, without a loop.由于print()会自动在参数之间添加空格,因此这是一种非常简洁易读的方法,无需循环。

>>> for i in range(5):
...    print(i, end=' ')
...
0 1 2 3 4 

Explanation: the sep parameter only affects the seperation of multiple values in one print statement.说明: sep参数只影响一个print语句中多个值的分离。 But here, you have multiple print statements with one value each , so you have to specify end to be a space (per default it's newline).但是在这里,您有多个打印语句,每个语句都有一个值,因此您必须将end指定为空格(默认情况下它是换行符)。

In Python 2.x, you could also do在 Python 2.x 中,你也可以这样做

for i in range(5):
    print i,

or要么

print " ".join(["%s"%i for i in range(5)])

Just add the space between quotes after the end.只需在结尾后的引号之间添加空格即可。 It should be:它应该是:

end = " "

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM