What is the numpy.array_str() function in Python?

Overview

The array_str() function in Python is used to return a string representation of the data in an array passed to it.

Syntax

numpy.array_str(a, precision=None, suppress_small=None)

Parameters

The array_str() function takes the following parameter values:

  • a: This represents the input array.
  • precision: This represents the floating point precision. This is optional.
  • suppress_small: This represents the numbers “very close” to zero as zero. It takes a Boolean value, and by default, the value is False. This is optional.

Return value

The array_str() function returns the string representation of the data in an array.

Example

import numpy as np
# creating an array
myarray = np.array([1, 2, 3, 4, 5])
# implementing the array_str() function
stringrep = np.array_str(myarray, precision = 6, suppress_small = True)
# printing the string representation
print(stringrep)
print(type(stringrep))
Implementing the numpy.array_str() function

Explanation

  • Line 1: We import the numpy module.
  • Line 4: We create an array myarray using the array() function.
  • Line 7: We implement the array_str() method on the given array using a precision of 6 and a suppress_small value as True. The output is assigned to a new variable stringrep.
  • Line 11: We print the array stringrep.
  • Line 12: Using the type() function, we obtain the data type of the array stringrep and print it.

Free Resources