简体   繁体   English

在python中打印没有换行的语句?

[英]Print statements without new lines in python?

I was wondering if there is a way to print elements without newlines such as 我想知道是否有一种方法可以打印没有换行符的元素,例如

x=['.','.','.','.','.','.']

for i in x:
    print i

and that would print ........ instead of what would normally print which would be 这将打印........而不是通常打印的内容

.
.
.
.
.
.
.
.

Thanks! 谢谢!

This can be easily done with the print() function with Python 3 . 使用Python 3使用print() 函数可以很容易地做到这一点。

for i in x:
  print(i, end="")  # substitute the null-string in place of newline

will give you 会给你

......

In Python v2 you can use the print() function by including: Python v2中 ,可以通过以下方式使用print()函数:

from __future__ import print_function

as the first statement in your source file. 作为源文件中的第一条语句。

As the print() docs state: print()文档所述

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Note, this is similar to a recent question I answered ( https://stackoverflow.com/a/12102758/1209279 ) that contains some additional information about the print() function if you are curious. 请注意,这类似于我最近回答的问题( https://stackoverflow.com/a/12102758/1209279 ),其中包含一些有关print()函数的其他信息print()如果您感到好奇)。

import sys
for i in x:
    sys.stdout.write(i)

or 要么

print ''.join(x)

I surprised no one has mentioned the pre-Python3 method for suppressing the newline: a trailing comma. 令我惊讶的是,没有人提到Python3之前的用于抑制换行符的方法:尾随逗号。

for i in x:
    print i,
print  # For a single newline to end the line

This does insert spaces before certain characters, as is explained here . 这确实插入空格前的某些字符,如解释在这里

As mentioned in the other answers, you can either print with sys.stdout.write, or using a trailing comma after the print to do the space, but another way to print a list with whatever seperator you want is a join: 如其他答案所述,您可以使用sys.stdout.write进行打印,也可以在打印后使用尾部逗号来分隔空格,但是使用所需分隔符打印列表的另一种方法是联接:

print "".join(['.','.','.'])
# ...
print "foo".join(['.','.','.'])
#.foo.foo.

For Python3: 对于Python3:

for i in x:
    print(i,end="")

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

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