简体   繁体   中英

How to remove the square brackets from a list when it is printed/output

I have a piece of code that does everything I need it to do and now I am making it look better and refining it. When I print the outcome, I find that the list in the statement is in square brackets and I cannot seem to remove them.

You can use map() to convert the numbers to strings, and use " ".join() or ", ".join() to place them in the same string:

mylist = [4, 5]
print(" ".join(map(str, mylist)))
#4 5
print(", ".join(map(str, mylist)))
#4, 5

You could also just take advantage of the print() function:

mylist = [4, 5]
print(*mylist)
#4 5
print(*mylist, sep=", ")
#4, 5

Note: In Python2, that won't work because print is a statement, not a function. You could put from __future__ import print_function at the beginning of the file, or you could use import __builtin__; getattr(__builtin__, 'print')(*mylist) import __builtin__; getattr(__builtin__, 'print')(*mylist)

If print is a function (which it is by default in Python 3), you could unpack the list with * :

>>> L = [3, 5]
>>> from __future__ import print_function
>>> print(*L)
3 5

You could convert it to a string instead of printing the list directly:

print(", ".join(LIST))

If the elements in the list are not strings, you can convert them to string using either repr() or str() :

LIST = [1, "printing", 3.5, { "without": "brackets" }]
print( ", ".join( repr(e) for e in LIST ) )

Which gives the output:

1, 'printing', 3.5, {'without': 'brackets'}

You could do smth like this:

separator = ','
print separator.join(str(element) for element in myList) 

Why don't you display the elements in the list one by one using the for loop instead of displaying an entire list at once like so:

# l - list
for i in range(0, len(l)):
    print l[i],

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM