tags:

views:

111

answers:

4

Is there anything that performs the following, in python? Or will I have to implement it myself?

array = [0, 1, 2]
myString = SOME_FUNCTION_THAT_TAKES_AN_ARRAY_AS_INPUT(array)
print myString

which prints

(0, 1, 2)

Thanks

+4  A: 

You're in luck, Python has a function for this purpose exactly. It's called join.

print "(" + ", ".join(array) + ")"

If you're familiar with PHP, join is similar to implode. The ", " above is the element separator, and can be replaced with any string. For example,

print "123".join(['a','b','c'])

will print

a123b123c
Dan Loewenherz
Does not work if array's items are not strings.
Alex Martelli
This will work in your example, but not in the one the submitter gave, since he used ints. You could use ", ".join([str(x) for x in array]) though.
jboxer
+4  A: 
SOME_FUNCTION_THAT_TAKES_AN_ARRAY_AS_INPUT = tuple
Alok
The OP claims he wants a string (though his use of `print` obfuscates that;-).
Alex Martelli
I know. My comment was more of a tongue-in-cheek remark, particularly because I got a kick out of his use of "SOME_FUNCTION_THAT_TAKES_AN_ARRAY_AS_INPUT". :-)
Alok
+4  A: 
def SOME_FUNCTION_THAT_TAKES_AN_ARRAY_AS_INPUT (arr):
    return str(tuple(arr))

Replace str with unicode if you need to.

jboxer
+1  A: 

If your array's items are specifically integers, str(tuple(array)) as suggested in @jboxer's answer will work. For most other types of items, it may be more of a problem, since str(tuple(...)) uses repr, not str -- that's really needed as a default behavior (otherwise printing a tuple with an item such as the string '1, 2' would be extremely confusing, looking just like a string with the two int items 1 and 2!-), but it may or may not be what you want. For example:

>>> array = [0.1, 0.2]
>>> print str(tuple(array))
(0.10000000000000001, 0.20000000000000001)

With floating point numbers, repr emits many more digits than make sense in most cases (while str, if called directly on the numbers, behaves a bit better). So if your items are liable to be floats (as well as ints, which would need no precaution but won't be hurt by this one;-), you might better off with:

>>> print '(%s)' % (', '.join(str(x) for x in array))
(0.1, 0.2)

However, this might produce ambiguous output if some of the items are strings, as I mentioned earlier!

If you know what types of data you're liable to have in the list which you call "array", it would give a better basis on which to recommend a solution.

Alex Martelli