一个打印函数中的 Python 打印数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20129415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python print array in one print function
提问by jonjohnson
For example I have an array of two elements array = ['abc', 'def'].
How do I print the whole array with just one function. like this: print "%s and %s" % arrayIs it possible? I have predefined number of elemnts, so i know how many elements would be there.
例如,我有一个包含两个元素的数组 array = ['abc', 'def']。如何仅使用一个函数打印整个数组。像这样:print "%s and %s" % array这可能吗?我已经预定义了元素的数量,所以我知道会有多少元素。
EDIT:
编辑:
I am making an sql insert statement so there would be a number of credentials, let's say 7, and in my example it would look like this:
我正在创建一个 sql insert 语句,因此会有许多凭据,假设为 7,在我的示例中,它看起来像这样:
("insert into users values(%s, \'%s\', ...);" % array)
采纳答案by pythoniku
you can also do
你也可以这样做
print '{0} and {1}'.format(arr[0],arr[1])
or in your case
或者在你的情况下
print "insert into users values({0}, {1}, {2}, ...);".format(arr[0],arr[1],arr[2]...)
or
或者
print "insert into users values({0}, {1}, {2}, ...);".format(*arr)
happy? make sure length of array matches the index..
快乐的?确保数组的长度与索引匹配..
回答by McAbra
Would
将
print ' and '.join(array)
satisfy you?
满足你?
回答by McAbra
You can use str.join:
您可以使用str.join:
>>> array = ['abc', 'def']
>>> print " and ".join(array)
abc and def
>>> array = ['abc', 'def', 'ghi']
>>> print " and ".join(array)
abc and def and ghi
>>>
Edit:
编辑:
My above post is for your original question. Below is for your edited one:
我上面的帖子是针对你原来的问题。以下是您编辑的一个:
print "insert into users values({}, {}, {}, ...);".format(*array)
Note that the number of {}'s must match the number of items in array.
请注意, 的数量{}必须与 中的项目数量相匹配array。
回答by krishna Prasad
If the input array is Integer typethen you have to first convert into string typearray and then use joinmethod for joining by ,or space whatever you want. e.g:
如果输入数组是整数类型,那么你必须先转换成字符串类型数组,然后使用join方法加入 by,或 space 任何你想要的。例如:
>>> arr = [1, 2, 4, 3]
>>> print(", " . join(arr))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
>>> sarr = [str(a) for a in arr]
>>> print(", " . join(sarr))
1, 2, 4, 3
>>>
回答by Michael Bietenholz
Another approach is:
另一种方法是:
print(" %s %s bla bla %s ..." % (tuple(array)))
where you need as many %sformat specifiers as there are in the array. The print function requires a tuple after the %so you have to use tuple()to turn the array into a tuple.
您需要%s与数组中一样多的格式说明符。打印函数需要在 之后的元组,%因此您必须使用tuple()将数组转换为元组。

