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)

5 Answers 5

11

Would

print ' and '.join(array)

satisfy you?

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

This is something more likely what I'm looking for, but if it's possible to just put an array at the end
Yes this what i was looking for!
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.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.