How to print text in the same line in Python

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

I wanted to print i on the same line without getting down, type replacing the current word

    
asked by anonymous 26.05.2017 / 20:14

2 answers

10

One solution is to use the end parameter of the print function equal to \r . This causes the pointer to return to the beginning of the same line; but this does not cause the line to be deleted. The lines would overlap one by one, and if a line attempts to overwrite a line larger than it, the garbage characters would be displayed. To make sure this does not occur, simply clear the current line with the 3[k character. See the example:

Given a phrases.txt file 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 do:

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("3[K", frase.strip(), end="\r")

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

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

See it working:

    
26.05.2017 / 22:13
4

Change your print (i) to

print(i, end=" ")

For Python 2 use:

print i,
    
26.05.2017 / 21:22