How to Convert Array to String in Python

To convert an array to a string in Python, you can use the join() function or the array2string() function.

The following examples show how to convert an array to a string in Python using these two methods.

Using join() Function

We can use the join() function to convert an array to a string.

Suppose we have the following array:

import array

# Create an array using the array module
array = array.array('i', [1, 2, 3, 4, 5])

# Convert the array to a string using the join() method
my_string = ', '.join(str(x) for x in array)

# Show string
print(my_string)

Output: 👇️

1, 2, 3, 4, 5

In the above code, the join() function is used to convert the array to a string.

Using array2string() Function

You can use the array2string() function to convert a NumPy array to a string in Python:

import numpy as np

# Create an array using the numpy module
array = np.array([1, 2, 3, 4, 5])

# Convert the array to a string using the array2string() method
my_string = np.array2string(array, separator=', ')

# Show string
print(my_string)

Output: 👇️

[1, 2, 3, 4, 5]

Here the output shows the string which is converted from the NumPy array using the array2string() function.

Conclusion

We can use the join() function or the array2string() function to convert an array to a string in Python. These methods provide a convenient way to transform arrays into strings.