我想知道是否有一种方法可以打印没有换行符的元素,例如
x=['.','.','.','.','.','.']
for i in x:
print i
Run Code Online (Sandbox Code Playgroud)
那将打印........
而不是通常会打印的内容
.
.
.
.
.
.
.
.
Run Code Online (Sandbox Code Playgroud)
谢谢!
Lev*_*von 17
使用Python 3的print() 函数可以轻松完成此操作.
for i in x:
print(i, end="") # substitute the null-string in place of newline
Run Code Online (Sandbox Code Playgroud)
会给你
......
Run Code Online (Sandbox Code Playgroud)
在Python v2中,您可以print()
通过包含以下内容来使用该功能:
from __future__ import print_function
Run Code Online (Sandbox Code Playgroud)
作为源文件中的第一个语句.
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
Run Code Online (Sandbox Code Playgroud)
请注意,这类似于我最近回答的问题(/sf/answers/847193091/),其中包含有关该print()
功能的一些其他信息(如果您感到好奇).
import sys
for i in x:
sys.stdout.write(i)
Run Code Online (Sandbox Code Playgroud)
要么
print ''.join(x)
Run Code Online (Sandbox Code Playgroud)
我很惊讶没有人提到用于抑制换行符的pre-Python3方法:一个尾随的逗号.
for i in x:
print i,
print # For a single newline to end the line
Run Code Online (Sandbox Code Playgroud)
这确实之前某些字符插入空格,如解释在这里.
归档时间: |
|
查看次数: |
16779 次 |
最近记录: |