简体   繁体   中英

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

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.

You can use repr, then remove all spaces:

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

Make sure you have no spaces in every element.

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