The simplest option is to use the .join()
method and the map()
function:
arr = [1, 2, 3, 4, 5]
result = ",".join(map(str, arr))
In Python, you can convert an array (or list) to a comma-separated string using the join()
method. Here are different ways to do it:
arr = [1, 2, 3, 4, 5]
result = ",".join(map(str, arr))
print(result) # Output: "1,2,3,4,5"
map(str, arr)
: Converts each element to a string.",".join(...)
: Joins the elements with a comma.If your list contains mixed data types (e.g., numbers, strings, None
, booleans), you can handle it like this:
arr = [1, "hello", None, True, 3.5]
result = ",".join(map(str, arr))
print(result) # Output: "1,hello,None,True,3.5"
str.join()
with a List of StringsIf the list already contains only strings, join()
can be used directly:
arr = ["apple", "banana", "cherry"]
result = ",".join(arr)
print(result) # Output: "apple,banana,cherry"
---arr = [1, 2, 3, 4, 5]
result = ",".join(str(x) for x in arr)
print(result) # Output: "1,2,3,4,5"
This method avoids map()
and is more readable for some developers.