python 2.7.5+ print list without spaces after the commas

做~自己de王妃 提交于 2019-12-06 10:17:16

问题


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


回答1:


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.




回答2:


You can use repr, then remove all spaces:

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

Make sure you have no spaces in every element.



来源:https://stackoverflow.com/questions/21660588/python-2-7-5-print-list-without-spaces-after-the-commas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!