3

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)
jonjohnson
  • 413
  • 1
  • 5
  • 18

5 Answers5

11

Would

print ' and '.join(array)

satisfy you?

rlms
  • 10,650
  • 8
  • 44
  • 61
McAbra
  • 2,382
  • 2
  • 21
  • 29
7

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..

pythoniku
  • 3,532
  • 6
  • 23
  • 30
2

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.

1

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
>>>
krishna Prasad
  • 3,541
  • 1
  • 34
  • 44
0

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.

thegreenogre
  • 1,559
  • 11
  • 22