NumPy | set_string_function method
Start your free 7-days trial now!
Numpy's set_string_function(~) method is used to customize how the string is printed.
Parameters
1. f | function or None
A function that takes as input an array, and returns a string. Setting None resets to the Numpy's default printing style.
2. reprlink | boolean | optional
Whether to change the print style for __repr__ or __str__. In essence, here's the difference:
set
Trueif you want to customise how an array is printed on screen without explicitprint(~)screen.set
Falseif you want to customise how the an array is printed when you call explicitly callprint(~).
By default, repr=True.
Return value
None.
Examples
Basic usage
By default, when you evaluate arrays, the output you see on the screen is as follows:
x = np.array([3,4,5])x
array([3, 4, 5])
We can modify this like so:
def my_print(arr): return "My array is: " + str(arr)
np.set_string_function(my_print)
Now, evaluating the array shows:
x
My array is: [3 4 5]
Here, we've used the default repr=True, and so the output of the print(~) function is unchanged:
print(x)
[3 4 5]
Specifying repr
Consider the case when we set repr=False:
def my_print(arr): return "Hello"
np.set_string_function(my_print, repr=False)
Now, since we've modified the __str__ instead of __repr__, the print function works differently:
x = np.array([3,4,5])print(x)
Hello
On the other hand, the output when evaluating a string is unaffected:
x
array([3, 4, 5])
Resetting to default
To reset the printing behavior to the default, pass in a None like so:
np.set_string_function(None)