0

I am running python 3.X, in console. Why does my typer's print make a new line for every character? Here is the code:

import msvcrt as m
def wait():
    m.getch()

print(" ")
string = """
code
"""

for i in string:
    wait()
    print(str(i).replace("\n", ""))

Here is the output:



c
o
d
e


Here is the output I want:


code

  • Take some time to look over the docs before asking here: https://docs.python.org/3/library/functions.html#print – 001 Oct 17 '19 at 16:29

4 Answers4

1

The print() function has an argument called end which is by default... You guessed it! '\n'.

If you don't want to have the default new-line, you can do:

print(..., end="")

So doing:

string = """
code
"""

for i in string:
    print(i, end="")

Gives:


code
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
0

print takes an optional keyword argument end, whose value defaults to \n'. You need to change that to the empty string. It's also simpler to just ignore i == "\n" rather than replace it with "".

for i in string():
    wait()
    if i != "\n":
        print(i, end='')
chepner
  • 497,756
  • 71
  • 530
  • 681
0

Ok, I figured it out on my own. having this:

print(someString, end=anything)

causes the output to not load in. This is because the code is buffering, and holds onto the output. My solution was to refresh my output every print, using sys.stdout.flush(). Here is the code that lets the output go:

import sys
sys.stdout.flush()

Here is my final "pretend-typer" code:

import msvcrt as m
import sys
def wait():
    m.getch()

print(" ")
stringy = """code"""

for i in stringy:
    wait()
    s = i
    print(s, end="")
    sys.stdout.flush()

Replace stringy with whatever you want the user to type. This does not work in emulators such as PyCharm or Eclipse, unless you run in console mode. This needs to be in a console.

0

Print has a flush method built-in with Python 3.3 and later. If using Python 3.3+ is an option, you should be able to skip calling sys.stdout.flush().

import msvcrt as m

def wait():
    m.getch()

print(" ")
my_string = "code"

for c in my_string:
    wait()
    print(str(c), end='', flush=True)
nBurn
  • 25
  • 5