How to remove square brackets and commas when printing a list in Python?

Asked

Viewed 1,486 times

1

How to remove brackets and commas from output when printing a list in Python? For example, I need the result of the code I did to look like this: 3 8 0 6 7 with numbers separated by space and just that, but the output is like this: [3, 8, 0, 6, 7]. How I remove this list formatting?

Code below:

numeros = input().split()
numeros = [int(x) for x in numeros]
maior_numero = max(numeros)

for i in range(len(numeros)):
    numeros[i] = maior_numero - numeros[i]

print(numeros)

2 answers

2


To display the results without brackets and comma, simply implement a repeat loop displaying the results on the same line, using the espaço as separator. In this case the code would be:

numeros = list(map(int, input().split()))

for i in range(len(numeros)):
    print(max(numeros) - numeros[i], end=' ')
print()

Just to clarify the first line of the code refers to a input() of multiple values. In this case, when we execute said code, the cursor is blinking in the upper left corner of the screen. At this time, we must type all the values, in same line, separated for a single space and press Enter.

From now on, a list will be mounted and stored in the variable numeros. Then the block for will scroll the range whose size is the list length numeros and, with each interaction, the difference between the maximum list value and its index value i.

2

A function called Join that can be useful in this case takes a list of strings and returns a string.

Within the function other functions are accepted:

partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',  
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 
'translate', 'upper', 'zfill ... entre outras.

code:

exemplo = [3, 8, 0, 6, 7]

# resultado em uma variavel
var1 = "".join(map(str,exemplo))
#resultado : '3 8 0 6 7'
#ou diretamente no print
"".join(map(str,exemplo))

Join accepts string.

Or you can use python’s uncompress medium to unzip the list and return all the elements from the list. represented by the asterisk (*) and the configuration 'Sep'.

print(*exemplo, sep=", ")

Browser other questions tagged

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