Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python 2.7.5+ print list without spaces after the commas

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

like image 524
user1614113 Avatar asked Dec 09 '25 22:12

user1614113


2 Answers

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.

like image 133
thefourtheye Avatar answered Dec 11 '25 13:12

thefourtheye


You can use repr, then remove all spaces:

>>> print repr([1,2]).replace(' ', '')
[1,2]

Make sure you have no spaces in every element.

like image 35
iMom0 Avatar answered Dec 11 '25 12:12

iMom0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!