Reputation: 423
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" % array
Is it possible? I have predefined number of elemnts, so i know how many elements would be there.
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:
("insert into users values(%s, \'%s\', ...);" % array)
Upvotes: 3
Views: 57961
Reputation: 1
Another approach is:
print(" %s %s bla bla %s ..." % (tuple(array)))
where you need as many %s
format 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.
Upvotes: 0
Reputation: 3812
If the input array is Integer type then you have to first convert into string type array and then use join
method for joining by ,
or space whatever you want. e.g:
>>> 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
>>>
Upvotes: 1
Reputation:
You can use 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
.
Upvotes: 2
Reputation: 3662
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..
Upvotes: 7