How to print in the same line in python?

Asked

Viewed 76 times

1

The function print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) has the argument end and by default end='\n', I know I change for end=' ' will print in the same line.

But I am advancing my knowledge in Python and thought about an activity that I need to 'print' in the same line a mathematical formula side by side, example:

 1       2       3
+1      +2      +3
--      --      --

Has some form of 'printar' of this formula above using a for more or less in this example "1 n+1 n-" or to achieve this effect I need to create an array and use two for (Rows,Columns) to 'print' the result I want?

I performed a test code. See here:

my_list=(["1 + 1","2 + 2","3 + 3"])
for i in my_list:
  print(i, end=" | ")

print("\n\n\n")
for j in my_list:
  print(f" {j.split()[0]}\n{j.split()[1]}{j.split()[2]}\n--", end="")

print("\n\n\n")
print("""
------Espectativa-----
 1     2    3
+1    +2   +3
--    --   -- 
""")

I want to understand if it is possible to do as an example.

  • 2

    For this specific case it could be something like this: https://ideone.com/S12uj7 - of course if the expressions can vary in size, have numbers with more than 1 digit, etc, then you would have to adapt

  • It worked as expected. I will try to understand what happens and in each part of the code to improve my knowledge. Thank you!

1 answer

3


The terminal seen by Python and other languages is always a set of lines from top to bottom - so if you have information that will be distributed in multiple rows, in parallel with information that should go in other columns, will always have to create first in memory a structure with all the information you want, and then print that structure line by line.

Something like:

my_list=(["1 + 1","2 + 2","3 + 3"])

saida = []

for elemento in my_list:
    linhas_por_elemento = elemento.split(" ", 1) # separa os elementos de exemplo - com a parte esperada em cada linha 
    for j, linha_do_elemento in enumerate(linhas_por_elemento):
        if len(saida) <= j:
            # a linha onde essa informação vai entrar ainda não foi criada:
            saida.append([])
        saida[j].append(linha_do_elemento)
# nesse ponto, a variável saída é uma lista de listas - onde cada elemento da mesma é uma lista com as strings que vão em cada coluna

# O print abaixo concatena com "|" os elementos de uma mesma linha, e concatena cada linha de texto com "\n":
    
print("\n".join("|".join(f"{elemento:>8s}" for elemento in linha) for linha in saida))

Alternatively, you can use a library that lets you use the terminal as a "2D output" - I develop the "finished" lib that allows this:

import terminedia as TM
sc = TM.Screen()

for coluna, elemento in enumerate(my_list):
    for linha, parte in enumerate(elemento.split(" ", 1)):
        sc.print_at((coluna * 8, linha), parte)

sc.update()

(just install the finished with "Pip install terminedia") The "sc" object allows treating the terminal as a 2D -e matrix print_at requires a tuple as the first parameter with the line coordinates, column where you want make the impression)

  • Very interesting, I saw that it is possible to use a for inside the print, I did not know it was possible. Can you point me to a book that teaches more complex functions? The courses I took never show more complex functions. I’m going to look up this lib you’re developing

  • 1

    "print" is a normal function. What is possible is to use a for within an expression. (print takes the output of the expression as a parameter). In this case, the expression with for is passed to the method join - what the join returns is what goes to the print. And then, finally, these for within expressions create the generator expressions

  • I think this answer here can explain well the Generator Expressions: https://answall.com/questions/193622/comorfunction-o-any-e-o-all-em-python/193625#193625

Browser other questions tagged

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