How to print text in the same line in Python

Asked

Viewed 4,736 times

7

    list = open("list.txt", "w")
    list = list.readlines()
    for i in list:
       print i

I would like to Print the value of i in the same line, without going down. Type replacing the current word.

  • Put an expected output example

2 answers

13

A solution is to use the parameter end of function print equal to \r. This causes the pointer to return to the beginning of the same line; however, this does not cause the line to be deleted. Lines would overwrite one by one and if a row occurs try to overwrite a line larger than it, characters rubbish would be displayed. To make sure this doesn’t happen, just clear the current line with the character \033[k. Take the example:

Considering an archive txt phrases. with the following content:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Integer vitae mi interdum mauris ultricies venenatis sit amet eget sapien.
Proin sit amet ante ornare, ornare lectus sit amet, faucibus velit.
Nulla ac risus sit amet tortor vulputate congue et id urna.
Proin et nisl non dui tristique pretium.
Etiam fringilla erat id ullamcorper euismod.
Donec accumsan dolor nec nibh dictum gravida.
Etiam sed lorem non leo condimentum dictum.
Donec posuere nisl in imperdiet molestie.
Donec vel metus sollicitudin, interdum odio non, egestas neque.
Donec eleifend odio laoreet consequat ornare.
Vestibulum rutrum metus nec sollicitudin condimentum.

We make:

import time

# Abre o arquivo frases.txt como leitura:
with open("frases.txt") as frases:

    # Percorre as linhas do arquivo:
    for frase in frases:

        # Limpa a linha atual, exibe a linha, retorna o ponteiro para o início:
        print("\033[K", frase.strip(), end="\r")

        # Tempo de 1s para poder visualizar a frase:
        time.sleep(1)

Important: we show the value of frase.strip(), because the phrase will have a character \n at its end and if we keep it, each line of the file will be displayed on a different line from the terminal. With the method strip we remove this character.

See working:

inserir a descrição da imagem aqui

  • 2

    It is worth talking about the character \b also - it returns a column the cursor, and also works on terminals where the ansi sequences are not active. (this doubt is frequent, I answered this in another question recently also)

  • @jsbueno Well remembered, I’ll see if I complete the answer

5

Change your print(i) to

print(i, end=" ")

For Python 2 use:

print i,
  • This solution will only display one line after another, similar to the concatenation process. The question asks for the previously displayed line to be deleted and replaced by the current one.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.