python 2.7.5+ print list without spaces after the commas

format, list, printing, python, python-2.7

Solution

The data in hand is a list of numbers. So, first we convert them to strings and then we join the join the strings with `str.join` function and then print them in the format `[{}]` using `str.format`, here `{}` represents the actual joined string.

data = [1,2, 3, 4]
print(data)                                       # [1, 2, 3, 4]
print("[{}]".format(",".join(map(repr, data))))   # [1,2,3,4]

data = ['aaa','bbb', 'ccc', 'ddd']
print(data)                                       # ['aaa', 'bbb', 'ccc', 'ddd']
print("[{}]".format(",".join(map(repr, data))))   # ['aaa','bbb','ccc','ddd']

If you are using strings

data = ['aaa','bbb', 'ccc', 'ddd'] print("[{}]".format(",".join(map(repr, data))))

Or even simpler, get the string representation of the list with `repr` function and then replace all the space characters with empty strings.

print(repr(data).replace(" ", ""))                 # [1,2,3,4]

Note: The replace method will not work if you are dealing with strings and if the strings have space characters in them.

Problem

I do ``` print [1,2] ``` But I want the print to output in the format [1,2] without the extra space after the comma. Do I need some "stdout" function for this?` Python 2.7.5+ (default, Sep 19 2013, 13:48:49) [GCC 4.8.1] on linux2

Original source