Problem with Python print formatting

Asked

Viewed 88 times

0

This code is to solve a problem of URI,o 1179, it gives error Presentation, because there is a space in the answers, between brackets, the problem is in the prints inside the loops for. Can you print without spaces? Type list[Indice] and not list[ Indice ] which is, how it appears?

par = []
impar = []

cont = 0
while cont < 15:
    n = int(input())
    if n % 2 == 0:
        par.append(n)
        if len(par) == 5:
            for i, pares in enumerate(par):
                print("par[",i,"] =", pares)
            par.clear()
    else:
        impar.append(n)
        if len(impar) ==5:
            for i, impares in enumerate(impar):
                print("impar[",i,"]=", impares)
            impar.clear()

    cont += 1
for i, impares in enumerate(impar):    
    print("impar[",i,"]=", impares)
for i, pares in enumerate(par):
    print("par[",i,"] =", pares)

2 answers

3

I’ve had this same mistake, and solved using the fstrings. put your prints in this format

for i, impares in enumerate(impar):
    print(f"impar[{i}]=", impares)

In this format spaces do not appear.

3


When you pass several parameters to the print, by default it puts a space between these parameters. But you can change this behavior by passing the parameter sep:

for i, impares in enumerate(impar):    
    print("impar[",i,"]=", impares, sep='')
for i, pares in enumerate(par):
    print("par[",i,"] =", pares, sep='')

So it uses the empty string ('') between the elements, that is, no more spaces.

But there are better alternatives, like format:

 print("par[{}]={}".format(i, pares))

Or, from Python 3.6, with f-string:

 print(f"par[{i}]={pares}")

Not directly related, but I suggest giving better names for variables, because This helps a lot when programming.

For example, lists could have plural names (impares and pares), because they may have more than one number. And we loops the variable can have the name in the singular, because at each iteration it represents a number. That is:

pares = []

...
for i, par in enumerate(pares):
    print(f"par[{i}]={par}")

Or else:

for i, numero in enumerate(pares):
    print(f"par[{i}]={numero}")

Browser other questions tagged

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