0

I'm writing a simple command line prompt script and noticed that lines printed immediately after doing a readline start with a leading space. Is there any way to avoid this behavior?

Sample function to demonstrate:

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

When I run this code I get:

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

1 Answers1

0

This is Python 2's "soft-space" behavior. After a print thing, statement, the next print will print a leading space to separate the output from the previous print output. This can look weird when a different text source, such as user input, causes the output of the two prints to appear on different lines.

There are various ways to get around soft-spacing, but here, the most appropriate would be to use raw_input instead of sys.stdin.readline. It auto-strips the newline for you and allows you to specify a prompt:

print 'Enter some text.'
foo = raw_input('> ')
print 'You entered "{0}"'.format(foo)
user2357112
  • 260,549
  • 28
  • 431
  • 505
  • Great, that fixed it. Wish I knew about raw_input before. I also found this related StackOverflow question when I Googled "python soft space" in case anyone else wants more info: http://stackoverflow.com/questions/255147/how-do-i-keep-python-print-from-adding-newlines-or-spaces – jzimbel Dec 03 '15 at 18:14