# NumPy array to a string in Python [6 Methods]

Do you want to convert a NumPy array to a string? In this Python article, I will explain how to convert a NumPy array to a string in Python using different methods with some demonstrative examples.

To convert a NumPy array to a string in Python, we can use the numpy.array2string function offers customizable string representations, while the built-in str function and numpy.array_str() provide simpler conversions. For a raw byte representation, numpy.ndarray.tostring is ideal. Alternatively, json.dumps can be used for JSON formatted strings, and list comprehension combined with the join function allows for custom string formatting.

## Methods to convert a NumPy array to a string in Python

There are six different methods to convert a NumPy array to a string in Python:

1. Using numpy.array2string
2. Using str Function
3. Using numpy.array_str()
4. Using numpy.ndarray.tostring
5. Using List Comprehension and join
6. Using json.dumps

Let’s see them one by one using some illustrative examples:

### 1. NumPy array to string using np.array2string() function

The numpy.array2string function is a straightforward way to convert a numpy array into a string. This method provides various formatting options.

This function converts the numpy array to a string in Python while preserving the array structure in the string format.

import numpy as np

states = np.array(['AL', 'AK', 'AZ', 'AR', 'CA'])
states_str = np.array2string(states)
print(states_str)
print("Type:", type(states_str))

Output:

['AL' 'AK' 'AZ' 'AR' 'CA']
Type: <class 'str'>

After implementing the code in the Pycharm editor, the screenshot is mentioned below.

### 2. Convert NumPy array to string using str() function

The built-in Python str() function can be used to convert a numpy array to a string in Python, directly converting the array’s default string format.

READ:  How to Create a Snake Game in Python Tkinter

For instance:

import numpy as np

temperatures = np.array([58.7, 55.0, 77.0, 71.6, 60.8])
temp_str = str(temperatures)
print(temp_str)
print("Type:", type(temp_str))

Output:

[58.7 55.  77.  71.6 60.8]
Type: <class 'str'>

A screenshot is mentioned below, after implementing the code in the Pycharm editor.

### 3. Python numpy array to string using numpy.array_str() function

The np.array_str() function is to convert a NumPy array to a string in Python. For example:

import numpy as np

populations = np.array([8.4, 3.9, 2.7, 1.5, 0.6])
pop_str = np.array_str(populations)
print(pop_str)
print("Type:", type(pop_str))

Output:

[8.4 3.9 2.7 1.5 0.6]
Type: <class 'str'>

After executing the code in Pycharm, one can see the output in the below screenshot.

### 4. NumPy to string using np.ndarray.tostring() function

The np.ndarray.tostring() method of an array provides a way to convert the numpy array to a string in Python. However, this method doesn’t convert the array into a human-readable string, but rather into a string representing the raw bytes in the array.

import numpy as np

usa_flag = np.array([[1, 0, 1], [0, 1, 0], [1, 0, 1]], dtype=np.uint8)
flag_str = usa_flag.tostring()
print(flag_str)
print("Type:", type(flag_str))

Output:

b'\x01\x00\x01\x00\x01\x00\x01\x00\x01'
Type: <class 'bytes'>

C:\Users\kumar\PycharmProjects\pythonProject1\main.py:4: DeprecationWarning: tostring() is deprecated. Use tobytes() instead.
flag_str = usa_flag.tostring()

Upon running the code in Pycharm, the resulting output is captured in the screenshot provided below.

### 5. np array to string using list comprehension and join() function

We can use list comprehension along with the join method of strings. This method is particularly useful when dealing with arrays of strings or when we need specific formatting.

This approach first converts each element of the array into a string using list comprehension and then concatenates these strings into a single, comma-separated string.

import numpy as np

scores = np.array([24, 17, 31, 20, 27])
scores_str = ', '.join([str(score) for score in scores])
print(scores_str)
print("Type:", type(scores_str))

Output:

24, 17, 31, 20, 27
Type: <class 'str'>

Below is a screenshot showcasing the result, following the implementation of the code in the Pycharm editor.

### 6. Convert np array to string using json.dumps() function

The json.dumps() method is used to convert the numpy array into a JSON-formatted string, which involves first converting the array to a Python list.

READ:  How to use Quill Editor in Django?

For example:

import numpy as np
import json

gdp = np.array([2.1e12, 3.2e12, 1.8e12, 2.9e12])
gdp_str = json.dumps(gdp.tolist())
print(gdp_str)
print("Type:", type(gdp_str))

Output:

[2100000000000.0, 3200000000000.0, 1800000000000.0, 2900000000000.0]
Type: <class 'str'>

Following the execution of the code within the Pycharm editor, a screenshot of the outcome is displayed below.

## Conclusion

Here, I have explained how to convert a NumPy array to a string in Python can be accomplished through a variety of methods. Whether we need a straightforward textual representation, a custom-formatted string, a raw binary format, or a JSON-compatible output, Python and NumPy provide flexible and efficient tools to achieve this.

The choice of method depends on the context of the data and the format in which the string representation is needed, offering Python users a versatile range of options for data manipulation and presentation.

You may also like to read these articles: