How to "properly" print a list?


So I have a list:

['x', 3, 'b']

And I want the output to be:

[x, 3, b]

How can I do this in python?

If I do str(['x', 3, 'b']), I get one with quotes, but I don't want quotes.

12/23/2017 4:51:20 PM

Accepted Answer

In Python 2:

mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))

In Python 3 (where print is a builtin function and not a syntax feature anymore):

mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))

Both return:

[x, 3, b]

This is using the map() function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join(). Then, the % string formatting operator substitutes the string in instead of %s in "[%s]".

6/20/2018 6:34:42 AM

This is simple code, so if you are new you should understand it easily enough.

    mylist = ["x", 3, "b"]
    for items in mylist:

It prints all of them without quotes, like you wanted.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow