Python end=' ' 到底是做什么的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20372485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does end=' ' exactly do?
提问by Pldx
So, I'm struggling trying to understand this kinda simple exercise
所以,我正在努力理解这个有点简单的练习
def a(n):
for i in range(n):
for j in range(n):
if i == 0 or i == n-1 or j == 0 or j == n-1:
print('*',end='')
else:
print(' ',end='')
print()
which prints an empty square. I tought I could use the code
打印一个空方块。我想我可以使用代码
print("*", ''*(n-2),"*")
to print the units in between the upper and the lower side of the square but they won't be aligned to the upper/lower side ones, which doesn't happen if you run the first code... so... could this be because of end=''or print()(would you be so kind and tell me what do they mean?)?
在正方形的上侧和下侧之间打印单位,但它们不会与上/下侧对齐,如果您运行第一个代码,则不会发生这种情况......所以......可以这样吗是因为end=''或print()(你会这么好心告诉我它们是什么意思吗?)?
采纳答案by starrify
Check the reference page of print. By default there is a newline character appended to the item being printed (end='\n'), and end=''is used to make it printed on the same line.
检查参考页print。默认情况下,要打印的项目会附加一个换行符 ( end='\n'),end=''用于使其打印在同一行上。
And print()prints an empty newline, which is necessary to keep on printing on the next line.
并print()打印一个空的换行符,这是在下一行继续打印所必需的。
EDITED:added an example.
Actually you could also use this:
编辑:添加了一个例子。
其实你也可以用这个:
def a(n):
print('*' * n)
for i in range(n - 2):
print('*' + ' ' * (n - 2) + '*')
if n > 1:
print('*' * n)
回答by Nilani Algiriyage
回答by Andrey Shokhin
print() uses some separator when it has more than one parameter. In your code you have 3 ("" is first, ''(n-2) - second, "*" -third). If you don't want to use separator between them add sep='' as key-word parameter.
print() 在有多个参数时使用一些分隔符。在您的代码中,您有 3 个(" " 是第一个,''(n-2) - 第二个,"*" - 第三个)。如果您不想在它们之间使用分隔符,请添加 sep='' 作为关键字参数。
print("*", ' '*(n-2), "*", sep='')
回答by volcano
print('\n'.join('*{}*'.format((' ' if 0<row<n-1 else '*')*n-2) for row in range(n)))
回答by user8683955
spam = ['apples', 'bananas', 'tofu', 'cats']
i = 0
for i in range(len (spam)):
if i == len(spam) -1:
print ('and', spam[i])
elif i == len (spam) -2:
print (spam [i], end=' ')
else:
print (spam [i], end=', ')
So I'm new to this whole coding thing, but I came up with this code. It's probably not as sophisticated as the other stuff, but it does the job.
所以我对这整个编码事情很陌生,但我想出了这段代码。它可能不像其他东西那么复杂,但它可以完成工作。

