How do I remove the last "," that appears in the print?

Asked

Viewed 155 times

1

How do I remove the last , that appears in the print?

x = int(input())
z = range(x)

for i in z:
    n = 2**i
    print(n, end=", ")

When I run the show he returns it to me:

1, 2, 4, 8, 16,
  • print(*[2**i for i in z], sep=",")

3 answers

4


To solve this problem we must devise a strategy so that we can print a comma after each value, except the last one.

One of the ways we can build the following strategy is by using the following code:

x = int(input())

for i in range(x):
    print(f'{2 ** i}, ' if i < x - 1 else f'{2 ** i}', end='')
print()

Note that inside the first print() we have a block if which will verify whether the value of i is less than x - 1. If so, the value will be displayed with a comma, i.e....

f'{2 ** i}, '

...otherwise it will display only the value - without the comma:

f'{2 ** i}'

Now, if by any chance, you wish to insert a ponto final after the último value, you can use the following code:

x = int(input())

for i in range(x):
    print(f'{2 ** i}, ' if i < x - 1 else f'{2 ** i}.', end='')
print()

Note that this code is similar to the previous one, with the only exception, when displaying the last value. Because, when displaying the last value, is also displayed the end point, ie:

f'{2 ** i}.'

Observing

The last print() serves only to skip a line, leaving the execution of the code more readable.

4

you can do the following:

for idx, i in enumerate(z):
    n = 2**i

    if idx == len(z)-1:
        print(n)
    
    else:
        print(n, end=", ")

using the method enumerate to find the last digit

or

for i in z:
    n = 2**i

    if z.index(i) == len(z)-1:
        print(n)
    
    else:
        print(n, end=", ")

the index

4

If you have an integer list, just use method str.join() to join them.

num_inteiros = int(input())
numeros = [str(2 ** i) for i in range(num_inteiros)]
print(", ".join(numeros))

I’m converting the numbers calculated to string for the method Join joins an iterable of strings and not integers.


In case you need to do with for, it’s easier to do the last print out of the loop than staying testing in all iterations if it is the last element of the range.

num_inteiros = int(input())

for i in range(num_inteiros - 1):
    print(2 ** i, end=", ")

print(2 ** (num_inteiros - 1))

Repl.it with the code working.

That way you would need to validate whether the number is greater than 0, but since you are not validating the input, I am assuming that the input will always be valid.

Browser other questions tagged

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