What is the numpy.fromstring() function from NumPy in Python?

Overview

In Python, the fromstring() function is used to create a new 1D (one-dimensional) array from a string that contains data.

Syntax

numpy.fromstring(string, dtype=float, sep)

Parameter value

The fromstring() function takes the following parameter values:

  • string: This represents the string that contains the data.
  • dtype: This represents the data type of the desired array. This parameter is optional.
  • sep: This represents the string that separates the numbers. The extra white space between the elements of the string is ignored. This parameter is optional.

Return value

The fromstring() function returns an output 1D array.

Code example

import numpy as np
# creating a string containing data
mystring = "1, 2, 3"
# implementing the fromstring() function
myarray = np.fromstring(mystring, dtype = int, sep = "," )
print(myarray)

Code explanation

  • Line 1: We import the numpy module.
  • Line 4: We create a string variable called mystring.
  • Line 7: We implement the fromstring() function on the string variable mystring with int as the data type and a comma (,), since we separate our strings with a comma. We assign the output to another variable called myarray.
  • Line 9: We print the new 1D array called myarray.

Free Resources