The fromstring() method creates a 1-D array from raw binary or text data in a string.
Note: fromstring() is usually used for numerical data and thus byte support has been deprecated.
fromstring() Syntax
The syntax of fromstring() is:
numpy.fromstring(string, dtype=float, count=-1, sep, like=None)
fromstring() Argument
The fromstring() method takes the following arguments:
string- the string to read (str)dtype(optional)- type of output array(dtype)count(optional)- number of items to read(int)sep- the sub-string separating elements in the string(str)like(optional)- reference object used for the creation of non-NumPy arrays(array_like)
Note: The default value of count is -1, which means all data in the buffer.
fromstring() Return Value
The fromstring() method returns an array from a string.
Example 1: Create an Array Using fromstring()
Output
[12. 13. 14. 15.] [12. 13. 14. 15.]
Example 2: Use dtype Argument to Specify Data Types
The dtype argument helps specify the required datatype of created numpy arrays.
Output
<string>:7: DeprecationWarning: The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead [1 2 3 4] <string>:11: DeprecationWarning: The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead [ 513 1027
Note: As mentioned above, fromstring() should only be used with numerical inputs and not byte strings.
When dtype = np.unit8, each byte in the byte string is interpreted as an 8-bit unsigned integer. Thus, array1 becomes [1 2 3 4].
When dtype = np.unit16, a byte-pair in byte string is interpreted as a 16-bit unsigned integer.
Thus, array2 has 2 elements \x01\x02 i.e. 2 * 256 + 1 = 513 and \x03\x04 i.e. 4 * 256 + 3 = 1027 and becomes [513 1027].
Example 3: Use count Argument to Limit the Data to Read
The count argument helps specify the number of items to read from the string.
Output
[1. 2. 3. 4.] [1. 2. 3.] [1. 2.]