如何防止 Python 打印添加换行符或空格?[重复]
- 2025-01-13 08:53:00
- admin 原创
- 146
问题描述:
在 Python 中,如果我说
print 'h'
我得到了字母 h 和一个换行符。如果我说
print 'h',
我得到了字母 h 而没有换行符。如果我说
print 'h',
print 'm',
我得到了字母 h、一个空格和字母 m。如何防止 Python 打印空格?
打印语句是同一循环的不同迭代,所以我不能只使用 + 运算符。
解决方案 1:
在Python 3中,使用
print('h', end='')
抑制行尾终止符,以及
print('a', 'b', 'c', sep='')
隐藏项目之间的空格分隔符。请参阅文档print
解决方案 2:
import sys
sys.stdout.write('h')
sys.stdout.flush()
sys.stdout.write('m')
sys.stdout.flush()
您需要调用sys.stdout.flush()
,因为否则它会将文本保存在缓冲区中,而您将看不到它。
解决方案 3:
Greg 是对的——你可以使用 sys.stdout.write
不过,也许你应该考虑重构你的算法来积累一个<whatevers>列表,然后
lst = ['h', 'm']
print "".join(lst)
解决方案 4:
或者使用+
,即:
>>> print 'me'+'no'+'likee'+'spacees'+'pls'
menolikeespaceespls
只要确保所有都是可连接的对象即可。
解决方案 5:
Python 2.5.2 (r252:60911, Sep 27 2008, 07:03:14)
[GCC 4.3.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print "hello",; print "there"
hello there
>>> print "hello",; sys.stdout.softspace=False; print "there"
hellothere
但实际上,你应该sys.stdout.write
直接使用。
解决方案 6:
为了完整性,另一种方法是在执行写入后清除软空间值。
import sys
print "hello",
sys.stdout.softspace=0
print "world",
print "!"
印刷helloworld !
不过,在大多数情况下,使用 stdout.write() 可能更方便。
解决方案 7:
这可能看起来很愚蠢,但似乎是最简单的:
print 'h',
print 'm'
解决方案 8:
重新控制您的控制台!只需:
from __past__ import printf
其中__past__.py
包含:
import sys
def printf(fmt, *varargs):
sys.stdout.write(fmt % varargs)
然后:
>>> printf("Hello, world!
")
Hello, world!
>>> printf("%d %d %d
", 0, 1, 42)
0 1 42
>>> printf('a'); printf('b'); printf('c'); printf('
')
abc
>>>
额外奖励:如果您不喜欢print >> f, ...
,您可以将此功能扩展为 fprintf(f, ...)。
解决方案 9:
我没有添加新答案。我只是将标记最佳的答案以更好的格式显示出来。我可以看到按评分显示的最佳答案是使用sys.stdout.write(someString)
。您可以尝试一下:
import sys
Print = sys.stdout.write
Print("Hello")
Print("World")
将产生:
HelloWorld
就这样。
解决方案 10:
在python 2.6中:
>>> print 'h','m','h'
h m h
>>> from __future__ import print_function
>>> print('h',end='')
h>>> print('h',end='');print('m',end='');print('h',end='')
hmh>>>
>>> print('h','m','h',sep='');
hmh
>>>
因此,使用 future 中的 print_function,您可以明确设置打印函数的sep和end参数。
解决方案 11:
您可以像 C 中的 printf 函数一样使用打印。
例如
打印“%s%s”%(x,y)
解决方案 12:
print("{0}{1}{2}".format(a, b, c))
解决方案 13:
sys.stdout.write
是(在 Python 2 中)唯一可靠的解决方案。Python 2 的打印功能太疯狂了。考虑以下代码:
print "a",
print "b",
这将打印a b
,让您怀疑它正在打印尾随空格。但这是不正确的。请尝试以下方法:
print "a",
sys.stdout.write("0")
print "b",
这将打印a0b
。您如何解释这一点?空格去哪儿了?
我还是不太明白这里到底发生了什么。有人能看看我的最佳猜测吗:
,
当您有尾随时,我尝试推断规则print
:
首先,让我们假设print ,
(在 Python 2 中)不会打印任何空格(空格或换行符)。
但是,Python 2 会注意您的打印方式 - 您使用的是print
、 还是sys.stdout.write
,还是其他什么?如果您连续两次调用print
,那么 Python 会坚持在两者之间添加一个空格。
解决方案 14:
print('''first line \nsecond line''')
它会产生
第一行 第二行
解决方案 15:
import sys
a=raw_input()
for i in range(0,len(a)):
sys.stdout.write(a[i])