Python 2.7.10: readline 在下一行导致前导 space

Python 2.7.10: readline causes a leading space on the following line

我正在编写一个简单的命令行提示脚本,并注意到在执行 readline 后立即打印的行以前导 space 开头。有什么办法可以避免这种行为吗?

要演示的示例函数:

import sys
def foo():
    print 'Enter some text.\n> ',
    bar = sys.stdin.readline()[:-1]
    print 'You entered "{0}"'.format(bar)

当我 运行 此代码时,我得到:

>>> foo()
Enter some text.
> Hi
 You entered "Hi"
^ the leading space I want to get rid of

这是 Python 2 的 "soft-space" 行为。在一个 print thing, 语句之后,下一个 print 将打印前导 space 以将输出与之前的打印输出分开。当不同的文本源(例如用户输入)导致两个 print 的输出出现在不同的行时,这看起来很奇怪。

有多种方法可以绕过软间距,但在这里,最合适的是使用 raw_input 而不是 sys.stdin.readline。它会自动为您去除换行符并允许您指定提示:

print 'Enter some text.'
foo = raw_input('> ')
print 'You entered "{0}"'.format(foo)