108

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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Obaid
  • 4,328
  • 9
  • 42
  • 42
  • To explain why the list isn't "properly" printed, `print(["Sam"])` calls `repr("Sam")`, which returns `'Sam'` (with the quotes), unlike when you call `print("Sam")` and python calls `str("Sam")` which returns `Sam` (without the quotes). See [difference between `str` and `repr`](https://stackoverflow.com/questions/1436703/difference-between-str-and-repr) or [Python `str` and `list`s](https://stackoverflow.com/questions/727761/python-str-and-lists) for more info. – LHeng Dec 01 '19 at 09:48

9 Answers9

202

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]".

fedorqui
  • 275,237
  • 103
  • 548
  • 598
SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304
  • 4
    Thank you that works great. Can you explain a bit in detail on what are you doing in the second line? I am new to python. – Obaid Mar 26 '11 at 23:12
  • 19
    He is using the `map` function to call `str` for each element of `mylist`, creating a new list of strings that he then joins into one string with `str.join`. Then, he uses the `%` string formatting operator to substitute the string in instead of `%s` in `"[%s]"`. – li.davidm Mar 26 '11 at 23:54
  • 6
    Another way to do it that's maybe a bit more modern: `"[{0}]".format(", ".join(str(i) for i in mylist))` – Jack O'Connor Sep 11 '13 at 13:25
  • 2
    i tend to prefer `map(f, xs)` (or `imap` in python2.x) over `(f(x) for x in xs)`, when `f` is a predefined callable; that tends to execute fewer bytecodes, and is usually more compact. Certainly *dont* `map(lambda x:..., xs)` thats much worse than `(... for x in xs)` – SingleNegationElimination Sep 11 '13 at 15:01
  • 1
    @user1767754: really? Link? – SingleNegationElimination Jun 16 '15 at 23:10
  • @li.davidm I included your explanation in the answer itself, since it is useful and was severly upvoted. Thanks for taking the time to explain this! – fedorqui Jun 20 '18 at 06:35
  • 1
    what about print(*mylist, sep=",")?¿?¿ – Temu May 01 '19 at 12:00
  • @user1767754 According to [the docs](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting), the only related things that seem to be deprecated are related to bytes: `b'%s'` and `b'%r'`. – Bernhard Barker Jun 23 '19 at 10:41
22

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

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

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

wjandrea
  • 28,235
  • 9
  • 60
  • 81
reemer9997
  • 341
  • 1
  • 4
  • 7
20

Using only print:

>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b
Finn
  • 1,999
  • 2
  • 24
  • 29
15

If you are using Python3:

print('[',end='');print(*L, sep=', ', end='');print(']')
Kabie
  • 10,489
  • 1
  • 38
  • 45
10

Instead of using map, I'd recommend using a generator expression with the capability of join to accept an iterator:

def get_nice_string(list_or_iterator):
    return "[" + ", ".join( str(x) for x in list_or_iterator) + "]"

Here, join is a member function of the string class str. It takes one argument: a list (or iterator) of strings, then returns a new string with all of the elements concatenated by, in this case, ,.

Seth Johnson
  • 14,762
  • 6
  • 59
  • 85
  • 2
    A good optimization for Python 2, since map returns a list in 2.x. It returns a generator in 3.x, so it doesn't help as much there. – Tom Zych Mar 27 '11 at 00:02
  • 7
    I would do return ``", ".join( str(x) for x in list_or_iterator).join('[]')`` – eyquem Mar 27 '11 at 12:23
  • @eyquem: Clever, I've not seen join used like that before. Still, that is a little more opaque to a beginner (since you're using the property that a string is an iterable container of one-character strings). – Seth Johnson Mar 27 '11 at 13:10
6

You can delete all unwanted characters from a string using its translate() method with None for the table argument followed by a string containing the character(s) you want removed for its deletechars argument.

lst = ['x', 3, 'b']

print str(lst).translate(None, "'")

# [x, 3, b]

If you're using a version of Python before 2.6, you'll need to use the string module's translate() function instead because the ability to pass None as the table argument wasn't added until Python 2.6. Using it looks like this:

import string

print string.translate(str(lst), None, "'")

Using the string.translate() function will also work in 2.6+, so using it might be preferable.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 2
    Alas : ``lst = ["it isn't", 3, 'b']`` ==> ``["it isnt", 3, b]`` and also with ``lst = ['it isn\'t', 3, 'b']`` – eyquem Mar 27 '11 at 12:20
  • 1
    @eyquem: Yes, avoiding the deletion of characters that are actually be part of your data (rather than strictly being used to delimit it) would naturally require slightly more elaborate/different logic if it's a possibility. – martineau Mar 27 '11 at 20:39
3

Here's an interactive session showing some of the steps in @TokenMacGuy's one-liner. First he uses the map function to convert each item in the list to a string (actually, he's making a new list, not converting the items in the old list). Then he's using the string method join to combine those strings with ', ' between them. The rest is just string formatting, which is pretty straightforward. (Edit: this instance is straightforward; string formatting in general can be somewhat complex.)

Note that using join is a simple and efficient way to build up a string from several substrings, much more efficient than doing it by successively adding strings to strings, which involves a lot of copying behind the scenes.

>>> mylist = ['x', 3, 'b']
>>> m = map(str, mylist)
>>> m
['x', '3', 'b']
>>> j = ', '.join(m)
>>> j
'x, 3, b'
Tom Zych
  • 13,329
  • 9
  • 36
  • 53
2

Using .format for string formatting,

mylist = ['x', 3, 'b']
print("[{0}]".format(', '.join(map(str, mylist))))

Output:

[x, 3, b]

Explanation:

  1. map is used to map each element of the list to string type.
  2. The elements are joined together into a string with , as separator.
  3. We use [ and ] in the print statement to show the list braces.

Reference: .format for string formatting PEP-3101

Ani Menon
  • 27,209
  • 16
  • 105
  • 126
0

I was inspired by @AniMenon to write a pythonic more general solution.

mylist = ['x', 3, 'b']
print('[{}]'.format(', '.join(map('{}'.format, mylist))))

It only uses the format method. No trace of str, and it allows for the fine tuning of the elements format. For example, if you have float numbers as elements of the list, you can adjust their format, by adding a conversion specifier, in this case :.2f

mylist = [1.8493849, -6.329323, 4000.21222111]
print("[{}]".format(', '.join(map('{:.2f}'.format, mylist))))

The output is quite decent:

[1.85, -6.33, 4000.21]
loved.by.Jesus
  • 2,266
  • 28
  • 34