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
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
SOME_FUNCTION_THAT_TAKES_AN_ARRAY_AS_INPUT = tuple
print obfuscates that;-).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.
str(array).