teolicht
teolicht

Reputation: 255

Is there a way to replace a previously outputted text in Python?

There is something I want to do, but unfortunately I have absolutely no idea on how to do it, and I doubt someone else has asked. So, basically, what I want is the program to output text in an previous area. I'll try to explain.

Let's say I outputted the following text to the screen:

===========================================================================================



===========================================================================================

My question is, is there a way, without using pygame, to replace the blank lines between the lines with a certain text WITHOUT printing the lines again? Is this possible using for example Python IDLE or directly in the terminal, or is it only possible using pygame or something "like" that?

It would look like this, for example:

===========================================================================================

Hello World!

===========================================================================================

Upvotes: 0

Views: 342

Answers (3)

DavidC.
DavidC.

Reputation: 677

Given your output, say, for example that is in a file test.dat:

===========================================================================================



===========================================================================================

a 1 simple line in vim would produce your desired output:

:3s/^$/Hello World!

If you want to automate this in a script: hello.sh

#!/bin/bash
ex test.dat <<-EOF
  :3s/^$/Hello World!
  wq " Update changes and quit.
EOF

Output:

===========================================================================================

Hello World!

===========================================================================================

Upvotes: 2

tobias_k
tobias_k

Reputation: 82889

You can use the curses library for this kind of text-only UI. Here's a simple example, first printing the horizontal lines, and then, after some time, adding a string on a previous line.

import time, curses

scr = curses.initscr()

scr.addstr(0, 0, "#" * 80)
scr.addstr(2, 0, "#" * 80)
scr.refresh()

time.sleep(1)

scr.addstr(1, 35, "Hello World")
scr.refresh()

Upvotes: 3

Sam Chats
Sam Chats

Reputation: 2321

While there should be multiple libraries to handle this task, you should check out curses and colorama. I'm unsure about curses but this is definitely possible with colorama (install it via pip).

Here's an example:

from colorama import *

def pos(x, y):
    return '\x1b['+str(y)+';'+str(x)+'H'

def display():
    init() #just for safety here; needed in Windows
    print(Fore.RED+pos(30, 10)+ 'This string is a different place!')

display()

Upvotes: 2

Related Questions