Python 3.8 - How to format the display of the elements of a list in column

Asked

Viewed 652 times

0

Hello.

My code currently:

To fill the list:

lista = []

def preenche_Lista():

        while True:
                espaco ="|______"
                nomeAluno = str(input('Qual o nome do estudante? - Digite FIM para encerrar -> ')).upper()
                elemento = nomeAluno+(espaco * 7)
                lista.append(elemento)
                if nomeAluno == "FIM":
                        break

To display the list:

def exibe_Lista(lista):
   x = 0
   print('Lista completa dos alunos cadastrados:\n{}'.format('*' * 50))
   while x < len(lista):
            elemento = lista[x]
            print(elemento)
            x += 1

With these two functions I am achieving this result:

inserir a descrição da imagem aqui

But the desired result is: inserir a descrição da imagem aqui

I’m a beginner in language so I have no idea where I can do this formatting. thank you in advance.

  • You need to find name that has more characters and then calculate the difference from the others and add the spaces depending on the difference.

  • There is a similar question: https://answall.com/questions/359166/formata%C3%A7%C3%A3o-de-sa%C3%Adda-de-dados-no-python

2 answers

3


In addition to the solution itself (how to properly format the output), there are other details to look at your code.

The function that fills the list is entering in the lista that was created outside the function. That is, this function only works for that specific list. What if you want another list? What if the list already has an element before? So the idea is that the function creates the list inside and returns it.

Not to mention, the way you did the loop, the string "FIM" is also inserted in the list, as if it were a student name. And input already returns a string, so do str(input()) is redundant and unnecessary.

Already to go through the list, you don’t need to use one while with the variable being incremented up to len(lista). In Python you can scroll through lists and other eternal objects with for...in.

And to format the data, just use the formatting options. Also, as you reported that you are using Python 3.8, you can now use f-strings (more details below).

But there is one small detail. A another answer suggested to use a fixed size, like 10, for example. But what if a name with more than 10 characters is typed? An alternative would be to choose a size "big enough" so that we "never" have a bigger name. But another alternative is to check the size of the names and use the largest of them as the size to be used in formatting.

Then it would look like this:

def preenche_lista():
    lista = [] # cria a lista dentro da função
    maior = 0
    while True:
        nome = input('Qual o nome do estudante? - Digite FIM para encerrar -> ').upper()
        if nome == "FIM": # se for "FIM", não insere na lista e retorna a lista e o maior tamanho
            return lista, maior
        if len(nome) > maior: # verifica se o nome digitado é o maior
            maior = len(nome)
        lista.append(nome)

# pega a lista de alunos e o tamanho do maior nome
alunos, tamanho = preenche_lista()

for aluno in alunos:
    # usa o tamanho do maior nome como o tamanho da formatação
    print(f'{aluno:<{tamanho}} ', '|_____' * 7, '|', sep='')

In doing {aluno:<{tamanho}}, the student’s name is aligned to the left, and tamanho specifies the size to be used for the name, filling in spaces if the name is smaller. The f before the quotation marks indicates that it is a f-string, which allows this syntax of placing the variable and formatting options between keys. Output example:

FULANO                       |_____|_____|_____|_____|_____|_____|_____|
CICLANO                      |_____|_____|_____|_____|_____|_____|_____|
ALCEBIADES DA SILVA DE SOUZA |_____|_____|_____|_____|_____|_____|_____|

If you want to keep the function that shows the students, the idea is that they receive as parameters the list and the size:

def exibe_lista(alunos, tamanho):
    print(f'Lista completa dos alunos cadastrados:\n{"*" * (44 + tamanho)}')
    for aluno in alunos:
        print(f'{aluno:<{tamanho}} ', '|_____' * 7, '|', sep='')

Then it would be enough to call:

alunos, tamanho = preenche_lista()
exibe_lista(alunos, tamanho)

Or else:

exibe_lista(*preenche_lista())

In this case, the asterisk serves for the values returned by preenche_lista (list and size) are passed as parameters to exibe_lista (see the documentation for more details). This form is interesting if you will not use these values for anything else (because then it is not worth saving them in variables).

Output example:

Lista completa dos alunos cadastrados:
************************************************************************
FULANO                       |_____|_____|_____|_____|_____|_____|_____|
CICLANO                      |_____|_____|_____|_____|_____|_____|_____|
ALCEBIADES DA SILVA DE SOUZA |_____|_____|_____|_____|_____|_____|_____|
  • Thank you very much. These two functions are part of another program, but with their touches I will optimize them as well as the program itself. valeu!

  • @Matheustaurino If the answer solved your problem, you can accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem. And when I get 15 points, you can also vote in all the answers you found useful.

0

Just use the method format with the type of formatting :< to add an X amount of spaces to the right of the string, if necessary. See the example code below:

alunos = []

for aluno in range(5):
    alunos.append(input(f"Digite o nome do {aluno + 1}º aluno: "))

for aluno in alunos:
    print("{:<10}".format(aluno), "|_____|" * 7)

Browser other questions tagged

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