新行上的 Python 打印语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20870744/
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
Python print statement on new line
提问by
I have a program that prints out strings from an array like this:
我有一个程序可以从这样的数组中打印出字符串:
for x in strings
print x,
Which works fine, the strings all print on the same line which is what I want, but then I also have to print out a string that isn't part of the array on a new line. Like this:
哪个工作正常,字符串都打印在我想要的同一行上,但是我还必须在新行上打印出一个不属于数组的字符串。像这样:
for x in strings:
print x,
print second_name
Which ends up all printing on the same line. I want second_name to print on a newline though, how do I do this?
最终所有打印都在同一行上。我希望 second_name 打印在换行符上,我该怎么做?
采纳答案by K DawG
Use the newline character \n:
使用换行符\n:
print '\n' + second_name
回答by K DawG
回答by Netch
The most direct solution is that if you used "print" without final newline in a cycle, add it after this cycle; so the code will look like
最直接的解决办法是,如果你在一个循环中使用了没有最后换行符的“print”,则在这个循环之后加上它;所以代码看起来像
for x in strings:
print x,
print ## this terminates the first output line
print second_name
This is kind of the most proper usage of print "API" according to its concepts.
根据其概念,这是打印“API”的最恰当用法。
OTOH the answer by K DawG does essentialy the same in other way, putting the default ending '\n' at beginning of the next "print", and, stream nature of stdout makes results of these two variants identical.
OTOH K DawG 的答案在其他方面也基本相同,将默认结尾 '\n' 放在下一个“打印”的开头,并且 stdout 的流性质使这两个变体的结果相同。
NB your construct isn't portable directly to Python3. Python2's print adds a space before each argument unless output isn't at beginning of line. Python3's separator is applied between arguments, but not before the first one in a line. So this manner (cloned from BASIC) isn't perspective and should be replaced with an own manner, like:
注意您的构造不能直接移植到 Python3。Python2 的打印在每个参数之前添加一个空格,除非输出不在行首。Python3 的分隔符应用于参数之间,但不在一行中的第一个之前。所以这种方式(从 BASIC 克隆)不是透视图,应该用自己的方式代替,比如:
out = ''
for x in strings:
out += ' ' + x
print(out[1:])
print(second_name)
but, " ".join(strings)is generally faster and more clear to read.
但是," ".join(strings)通常阅读速度更快,更清晰。

