Where is this \n coming from in my arrays (Python)?

Viewed 276

I'm trying to create a text string for the following numpy array:

A = array([0, 0, 0, 0, 0.64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0])

I can do this easily with this line of code:

text = f'{A}'

The problem I'm having is that whenever I use this f'{}' to create a string from an array, it outputs the same array, but with a \n after some characters:

text
'[0.   0.   0.   0.64 0.   0.   0.   0.   0.   0.   0.   0.   0.   0.\n 1.   0.   0.   0.  ]'

I'm trying to use this array in the title of a plot, so I don't want the array to be text wrapping onto a new line because it makes it confusing to read/see.

I've tried using rstrip('\n') on text but it doesn't remove the '\n'. Does anyone have any idea what's going on? Why is this \n popping up in the string array?

2 Answers

You don't need to declare array() to accomplish what you are trying to do:

A = [0, 0, 0, 0, 0.64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]

print(A)
[0, 0, 0, 0, 0.64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]

print(f'{A}')
[0, 0, 0, 0, 0.64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0] 

A
[0, 0, 0, 0, 0.64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]

It seems like you are creating a NumPy N-dimensional array there and then converting it to a string, so it is printing the string representation of that array when you call print(). Unless you specifically need a NumPy array, you can do it just like I have above, or if you need to:

    from numpy import array
    A = [0, 0, 0, 0, 0.64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
    B = array(A)

    print(B)
    [0.   0.   0.   0.   0.64 0.   0.   0.   0.   0.   0.   0.   0.   0.
     0.   1.   0.   0.   0.  ]

    print(f'{B}')
    [0.   0.   0.   0.   0.64 0.   0.   0.   0.   0.   0.   0.   0.   0.
     0.   1.   0.   0.   0.  ]

     B
     array([0.  , 0.  , 0.  , 0.  , 0.64, 0.  , 0.  , 0.  , 0.  , 0.  , 0.  ,
       0.  , 0.  , 0.  , 0.  , 1.  , 0.  , 0.  , 0.  ])

If you absolutely have to render a NumPy array as a string, then you can do something like this:

  text = f'{A}'
  text = text.replace("\n","")

Or as Ramón Márquez also mentioned, you can simply increase the printoptions line width:

numpy.set_printoptions(linewidth=96)

Documentation on NumPy arrays: https://machinelearningmastery.com/gentle-introduction-n-dimensional-arrays-python-numpy/

Documentation on NumPy print options: https://numpy.org/doc/1.18/reference/generated/numpy.printoptions.html

Related