Printing and prompting adds a mysterious extra space

Discussion in 'Python' started by Christoph Haas, Oct 1, 2005.

  1. Evening...

    I'm writing a simple interactive program to maintain a database.
    The goal was to print "> " at the beginning of the line, wait for
    user input and then deal with it. Minimal test program:

    import sys; print ">", ; print sys.stdin.readline()

    However when I run the program and enter "foobar" it looks like this:

    ^----------- where does this space come from?

    I wonder where the space comes from in the line where I print what the
    user typed. Does it have to do with the "," after the print which I use
    to suppress the newline? Any ideas?

    Christoph Haas, Oct 1, 2005
    1. Advertisements

  2. Christoph Haas

    mensanator Guest

    Another question you could ask is: why is there NO space after
    the '>'? Have a look at this.

    import sys

    print ">",

    s = sys.stdin.readline()

    print len(s)
    print s
    for i in s:
    print ord(i),i

    Instead of printing the input, I'm assigning it to a variable.
    Notice that the extra space appears on the next print statement
    and is not part of the input. this is verified by showing that
    the input has exactly 4 characters and is "huh\n".

    104 h
    117 u
    104 h

    So it looks like the space was sitting in the output buffer.
    mensanator, Oct 1, 2005
    1. Advertisements

  3. Yes, probably. But how do I get that buffer flushed? I tried
    sys.stdout.flush() after the print statement but it wasn't printed,
    either. I probabl need something like...

    print "> "+

    instead of

    print ">",

    How could I solve that decently?

    Christoph Haas, Oct 1, 2005
  4. Christoph Haas

    jepler Guest

    Use sys.stdout.write instead of print. It will solve these problems you are

    If you really want to know what's going on, read the language manual, It explains the behavior of this extra
    space, which is output by a successive 'print' statement. The implementation
    uses an attribute called 'softspace', which is described in


    Version: GnuPG v1.4.1 (GNU/Linux)

    -----END PGP SIGNATURE-----
    jepler, Oct 1, 2005
  5. Thank you for the technical explanation. "print a,b" is nice to read
    in simple Python programs. But when you need to get more control of
    I/O it's better to know what's really happening inside.

    So the "softspace" is always added after a "print a," statement but only
    printed if Python thinks it is not at the beginning of a terminal line.

    Again, thanks. I'll rest my case.

    Christoph Haas, Oct 2, 2005
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.