Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to print a 2D array in Python with ANSI formatting codes without having to iterate through every element is to use the NumPy library. NumPy is a popular Python library used for numerical computing and provides a convenient way to apply formatting codes to entire arrays.

Here is an example code snippet that demonstrates how to print a 2D NumPy array with red text:

import numpy as np

# create a 2D array
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# apply ANSI formatting codes to the entire array
red_text = '\033[31m{}\033[0m'
formatted_arr = np.array([red_text.format(val) for val in arr.flatten()]).reshape(arr.shape)

# print the formatted array
print(formatted_arr)

In this example, the NumPy flatten() method is used to convert the 2D array into a 1D array, which is then iterated over to apply the red text ANSI code to each element. The reshape() method is then used to convert the 1D array back into a 2D array with the same shape as the original. Finally, the formatted array is printed using the print() function.