1

I'm learning Python and for my homework I wrote a simple script that get a string from user like this one: aaaabbbbcccdde and transforms it to a4b4c3d2e1. Now I've decided to get things more interesting and modified code for continuous input and output in realtime. So I need a possibility to enter symbols and get an output coded with that simple algorithm.

The only problem I've faced with I needed output without '\n' so all the coded symbols were printed consequently in one string e.g: a4b4c3d2e1

But in that case output symbols mixed with my input and eventually the script froze. Obviously I need Enter symbols for input on one string and output it on another string w/o line breaks.

So, could you tell me please is it possible without a lot of difficulties for newbie make up a code that would do something like this:

a - #here the string in shell where I'm always add any symbols

a4b4c3d2e1a4b4c3d2e1a4b4c3d2e1 - #here, on the next string the script continuously outputs results of coding without breaking the line.

import getch

cnt = 1

print('Enter any string:')

user1 = getch.getch()

while True:
    buf = getch.getch()
    if buf == user1:
       cnt += 1
       user1 = buf
    else:
       print(user1, cnt, sep='')
       user1 = buf
       cnt = 1

so this snippet outputs me something like this:

a4

s4

d4

f4

etc

And in all cases when I'm trying to add end='' to output print() the program sticks.

What is possible to do to get rid of that? Thanks !

SWANSE
  • 9
  • 2

1 Answers1

0

I don't really know the details but I can say that: when you add end='', the program don't freeze, but the output (stdout) does not refresh (maybe due to some optimisation ? I really don't know).

So what you want to do is to flush the output right after you print in it.

print(user1, cnt, sep='', end='')
sys.stdout.flush()

(It is actually a duplicate of How to flush output of print function? )

mistiru
  • 2,996
  • 3
  • 11
  • 27