[英]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. 但是我希望打印输出以[1,2]格式输出,逗号后没有多余的空格。
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 linux2上的Python 2.7.5+(默认值,2013年9月19日,13:48:49)[GCC 4.8.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. 因此,首先我们将它们转换为字符串,然后使用
str.join
函数将字符串连接str.join
,然后使用str.format
以[{}]
格式打印它们,其中{}
代表实际的连接字符串。
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)))) 数据= ['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. 甚至更简单,使用
repr
函数获取列表的字符串表示形式,然后用空字符串替换所有空格字符。
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. 注意:如果您正在处理字符串并且字符串中包含空格字符,则replace方法将不起作用。
You can use repr, then remove all spaces: 您可以使用repr,然后删除所有空格:
>>> print repr([1,2]).replace(' ', '')
[1,2]
Make sure you have no spaces in every element. 确保每个元素中都没有空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.