Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk4 min

How to Convert a NumPy Array to a String in Python: Choose the Right Method

Choose the right NumPy conversion for display, JSON, element-wise text, joined values, or binary data, with examples and key limitations.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To convert a NumPy array to a string in Python, first decide whether you need readable display text, structured data for JSON, a string for each element, one custom joined string, or raw bytes. For a quick display, use str(arr); for JSON, serialize arr.tolist(); for binary data, use arr.tobytes(). These outputs are not interchangeable.

Examples below use arr = np.array([[1, 2], [3, 4]]). The right method depends on what you intend to do with the result:

As an Amazon Associate I earn from qualifying purchases.

  • Show the values to a person: use NumPy’s display formatting.
  • Exchange structured data: convert to Python values and serialize them, for example as JSON.
  • Make each value text: convert elements individually, or join them into one string.
  • Store or transmit the underlying data as binary: use a bytes-producing method, not a text formatter.

1. Use str(arr) for a quick display

str(arr) returns NumPy’s usual readable representation. For example:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import numpy as np

arr = np.array([[1, 2], [3, 4]])
text = str(arr)
print(text)

This is convenient for logs, debugging, or display. It is presentation text, not a stable serialization format: NumPy’s print settings, precision, and line wrapping can affect how arrays are shown, and large arrays may be summarized. See NumPy’s print options and array formatting documentation.

2. Choose a NumPy representation function for display

NumPy provides functions for returning formatted text directly. They differ in how much control they offer and what information their output emphasizes.

Method What it returns Best suited to
np.array_str(arr) A string focused on the array’s data A concise data display
np.array_repr(arr) A representation that can include array and dtype details Inspecting what the object is
np.array2string(arr, ...) A string with configurable formatting Controlling separators, precision, or line width

np.array_str(arr): focus on the data

np.array_str(arr) returns the array data as a single string. It is similar to array_repr, but does not include the same array-kind information. This remains display text rather than JSON or a general interchange format. See NumPy’s array_str documentation.

np.array_repr(arr): include representation details

np.array_repr(arr) returns a representation of the array that may show its type or dtype. This can help when inspecting an object, but the result is not JSON. For example, a NumPy-style representation such as array([1, 2]) uses syntax that JSON does not accept. See NumPy’s array_repr documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

np.array2string(arr, ...): control formatting explicitly

Use np.array2string when you need to set formatting options such as the separator, precision, or line width:

text = np.array2string(arr, separator=', ', precision=2)

The function also supports custom formatters and a summarization threshold. Its default precision is tied to NumPy’s print options; rounding a displayed float to a low precision can hide detail, so do not use formatted output as a lossless numeric record. See the array2string reference.

3. Convert to nested Python values for JSON

For JSON text, convert the array to Python lists and scalars with tolist(), then pass the result to Python’s JSON serializer:

import json

json_text = json.dumps(arr.tolist())

For the example array, the serialized data has nested lists, preserving its two-dimensional arrangement. NumPy documents tolist() as returning a nested list with one level per array dimension and Python scalars at the leaves. The array’s NumPy dtype is not thereby preserved as metadata. Check the scalar types and handling of non-finite values for your application rather than assuming every array can be represented losslessly in JSON. See NumPy’s tolist documentation and Python’s JSON documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

4. Convert each element to text or join values into one string

These are two different goals: element-wise conversion retains an array structure, while joining produces one scalar string.

Element-wise string conversion

Use astype(str) when you want a string value for each element:

string_array = arr.astype(str)

The result is still an array, now containing strings; it is not one Python string containing the whole array. NumPy string dtypes can have fixed widths, so inspect the resulting dtype and confirm behavior for the NumPy version and values you use. See the astype documentation.

One custom joined string

For a simple one-off string, flatten the values for iteration and join their text with a delimiter:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
joined = ', '.join(map(str, arr.flat))

For the example, this yields 1, 2, 3, 4. Joining discards the original shape, and a delimiter can make the result ambiguous if values themselves contain that delimiter. If you need to reconstruct the data, preserve the shape and define an escaping or encoding scheme instead of relying on a bare joined string.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

5. Use tobytes() for raw binary data, not readable text

arr.tobytes() returns Python bytes containing the array’s raw data; it does not turn numbers into readable numerals. Its default traversal order is C order, and the order argument controls the traversal. Binary decoding requires compatible dtype, byte order, shape, and layout information; the bytes alone do not describe all of that. NumPy documents frombuffer for constructing an array from a buffer when the correct interpretation is known. See the tobytes documentation and frombuffer documentation.

Use tobytes() in new code. The older tostring() spelling has been deprecated since NumPy 1.19; see the NumPy 2.0 documentation.

Which method should you use?

Your goal Use What to keep in mind
Display an array quickly str(arr) Output is for presentation and can depend on formatting settings.
Display data with explicit formatting np.array_str(arr) or np.array2string(arr, ...) array2string offers formatting controls.
Inspect an array representation np.array_repr(arr) Representation syntax is not JSON.
Produce JSON text json.dumps(arr.tolist()) Check type and non-finite value handling for your use case.
Convert values individually to strings arr.astype(str) The result remains an array; check string dtype width.
Make one delimited text field ', '.join(map(str, arr.flat)) Shape is lost unless stored separately.
Get raw binary data arr.tobytes() The result is bytes, and decoding needs metadata.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.