Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print() to previous line?

I need command that writes to previous line, like print() without \n.

Here is some example code:

a=0

print("Random string value")

if a==0:
    print_to_previous_line("is random")

and output

Random string value is random

i know that i can do like print("string", value) to use multipile different things in same print command, but that is not the answer. Reason is too messy to be explained here, but this "print to previous line" will be exactly right answer. So what would it be in reality?

like image 639
Jabutosama Avatar asked Nov 02 '14 08:11

Jabutosama


2 Answers

In Python 3, you can suppress the automatic newline by supplying end="" to print():

print("Random string value", end="")
if a==0:
    print(" is random")
else:
    print()

See How to print without newline or space?

like image 179
NPE Avatar answered Sep 21 '22 13:09

NPE


There are times when you cannot control the print statement that proceeds yours (or doing so may be difficult). This then will:

  • go to the (start of the) previous line: \033[F
  • move along ncols: \03[{ncols}G
  • start printing there.

print(f"\033[F\033[{ncols}G Space-lead appended text")

I have not found a way of going to the "end" of the previous line, but you can specify a value of ncols which is greater that the length of the previous line. If it's shorter that the previous line, you will end up overwriting what was there.

like image 36
Enda Farrell Avatar answered Sep 22 '22 13:09

Enda Farrell