Print() to previous line?

Question:

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?

Asked By: Jabutosama

||

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?

Answered By: NPE

I would suggest using the print statement, like this

print("This is a text",end=" ")

The end=" " says, that the string isnĀ“t ‘complete’ and the next print statement needs to come in the same Line. The String " " means, that it should leave a space between this String and the String in the next print statement. Alternatively, you could use end="" too.
I hope this Helped!

Answered By: user4204019

I would suggest printing a statement like this first:

print("Some stuff here", end=" ")

Then I would use an if statement like this:

if stuff:
     print("Text you want displayed on same line")
else:
     print("")
     print("Text you want displayed on next line")
Answered By: Meh

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: 33[F
  • move along ncols: 3[{ncols}G
  • start printing there.
print(f"33[F33[{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.

Answered By: Enda Farrell
def Fib(n):
    a,b = 0,1
    c=','
    while(a<n):
       print(a, end='')   # Way to print in same line
       a,b = b, a+b
       if a<n:
         print(c, end=',') # Way to ensure keep printing in same line
Fib(1000)
Answered By: user14413410
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.