[英]Print statements without new lines in python?
我想知道是否有一種方法可以打印沒有換行符的元素,例如
x=['.','.','.','.','.','.']
for i in x:
print i
這將打印........
而不是通常打印的內容
.
.
.
.
.
.
.
.
謝謝!
使用Python 3使用print() 函數可以很容易地做到這一點。
for i in x:
print(i, end="") # substitute the null-string in place of newline
會給你
......
在Python v2中 ,可以通過以下方式使用print()
函數:
from __future__ import print_function
作為源文件中的第一條語句。
如print()文檔所述 :
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
請注意,這類似於我最近回答的問題( https://stackoverflow.com/a/12102758/1209279 ),其中包含一些有關print()
函數的其他信息print()
如果您感到好奇)。
import sys
for i in x:
sys.stdout.write(i)
要么
print ''.join(x)
令我驚訝的是,沒有人提到Python3之前的用於抑制換行符的方法:尾隨逗號。
for i in x:
print i,
print # For a single newline to end the line
這確實插入空格前的某些字符,如解釋在這里 。
如其他答案所述,您可以使用sys.stdout.write進行打印,也可以在打印后使用尾部逗號來分隔空格,但是使用所需分隔符打印列表的另一種方法是聯接:
print "".join(['.','.','.'])
# ...
print "foo".join(['.','.','.'])
#.foo.foo.
對於Python3:
for i in x:
print(i,end="")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.