How to stop the end='' command in Python

Asked

Viewed 6,310 times

3

I got a problem every time I use the remote end='' he does not stop!

Example:

tabela = ('Palmeiras', 'Flamengo', 'Internacional')
for time in tabela:
    print(time, end=' ')
print('=-' * 20)

Execution:

Palmeiras Flamengo Internacional =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

Since I wanted this one =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- at the bottom line

5 answers

4

What happens is that when you change the value of end in the function, it removes the automatic line break because its default value is '\n'

So print('foo') as well as print('foo', end='\n') writes "foo n" and print('foo', end=' ') writes "foo "

If you want to add this line break just do print('\n', '=-' * 20), so it will print the line break and then the string =- repeated 20 times

3


Another important point is that you don’t need to make a repeat loop just to display the values of the tuple. You can generate the string from the method str.join:

tabela = ('Palmeiras', 'Flamengo', 'Internacional')

print(' '.join(tabela))
print('=-' * 20)

This generates the output:

Palmeiras Flamengo Internacional
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  • 1

    Strange, I had tried it and tabela.join(' ') in an online console and had given error. Dai gave a searched and, from what I understand, tuples do not have the method join, I switched the () for [] so it worked

  • 2

    @And it doesn’t have the method join is from string, who receives an eternal.

1

Another solution is to prepare a string and print everything at once

tabela = ('Palmeiras', 'Flamengo', 'Internacional')
s = ''
for time in tabela:
    s += time + ' '
print(s[:-1]) # a parte `[:-1]` tira o ultimo espaço da string
print('=-' * 20)

1

Friend, I was able to solve using the Costamilam tip. I just assigned the ' n' value back to the end:

lista = ('Palmeiras', 'Flamengo', 'Internacional')
for time in lista:
  print(time, end=(" "))
print(end=('\n'))
print('=-' * 20)

Returns:

Palmeiras Flamengo Internacional 
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 

1

For you to resolve this issue, one of the ways I suggest is to add a print vazio,that is to say, "print()" before your last print.

The algorithm would look like this...

tabela = ('Palmeiras', 'Flamengo', 'Internacional')
for time in tabela:
    print(time, end=' ')
print()
print(f'{"=-" * 20}\n')

Another way to resolve this issue is:

tabela = ('Palmeiras', 'Flamengo', 'Internacional')
print(*tabela)
print('=-' * 20)
print()

Browser other questions tagged

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