When you are dealing with large arrays, and you want to print the whole array for debugging, the default printing with line breaks can take up to lots of vertical spaces. Printing without line breaks provides a more compact representation.
To print numpy objects without line breaks, you can use np.array_repr() with .replace() methods or np.array2string() with formatting.
With line breaks, the numpy array (object) looks like this:
Without line breaks, the numpy array (object) looks like this:
Method 1: Using np.array_repr() with .replace()
The numpy.array_repr() function converts an array into a string means it returns a string representation of the array.
After converting it into a string, we can further apply the .replace() function to replace the line break character (“\n”) with an empty space(“), effectively removing the line breaks.
import numpy as np arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) # Printing an array (with line breaks) print("With line breaks:") print(arr) # Printing an array without line breaks (using np.array_repr and replace) print("\nWithout line breaks:") arr_str = np.array_repr(arr).replace('\n', '') print(arr_str)
Output
With line breaks: [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]] Without line breaks: array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]])
Method 2: Using np.array2string() with formatting
The np.array2string() method also does the same conversion as the np.array_repr() function, which converts an array into a string with the exception of allowing us to specify the separator between elements.
Then, we can use the .replace() method to replace line breaks with empty string.
import numpy as np arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) # Printing an array (with line breaks) print("With line breaks:") print(arr) # Printing without line breaks (using np.array2string with replace()) print("\nWithout line breaks (using array2string):") arr_str_2 = np.array2string(arr, separator=', ').replace('\n', '') print(arr_str_2)
Output
With line breaks: [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]] Without line breaks (using array2string): [[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]]
That’s all!