NumPy Input and Output: set_string_function() function
numpy.set_string_function() function
The set_string_function() function is used to set a Python function to be used when pretty printing arrays.
Syntax:
numpy.set_string_function(f, repr=True)
Version: 1.15.0
Parameter:
Name | Description | Required / Optional |
---|---|---|
f | Function to be used to pretty print arrays. The function should expect a single array argument and return a string of the representation of the array. If None, the function is reset to the default NumPy function to print arrays. function or None |
Required |
repr | If True (default), the function for pretty printing (__repr__) is set, if False the function that returns the default string representation (__str__) is set. bool |
Optional |
NumPy.set_string_function() method Example-1:
>>> import numpy as np
>>> def pprint(arr):
... return 'Hurrah! We won the game!'
...
>>> np.set_string_function(pprint)
>>> x = np.arange(12)
>>> x
Output:
Hurrah! We won the game!
>>>> import numpy as np
>>> def pprint(arr):
... return 'Hurrah! We won the game!'
...
>>> np.set_string_function(pprint)
>>> x = np.arange(12)
>>> print(x)
Output:
[ 0 1 2 3 4 5 6 7 8 9 10 11]
We can reset the function to the default:
>>> np.set_string_function(None)
>>> x
Output:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
NumPy.set_string_function() method Example-2:
repr affects either pretty printing or normal string representation. Note that __repr__ is still affected by setting __str__
because the width of each array element in the returned string becomes equal to the length of the result of __str__().
>>> import numpy as np
>>> x = np.arange(5)
>>> np.set_string_function(lambda x:'random', repr=False)
>>> x.__str__()
Output:
'random'
>>> x.__repr__()
Output:
'array([0, 1, 2, 3, 4])'
Python - NumPy Code Editor:
Previous: get_printoptions() function
Next: printoptions() function
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/numpy/input-and-output/set_string_function.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics