pythonnumpy-ndarrayf-string

How to reduce verbosity of self-documenting expressions in Python f-strings?


This script:

import numpy as np

a = np.array([2, 3, 1, 9], dtype='i4')
print(a)
print(f'{a=}')

produces:

[2 3 1 9]
a=array([2, 3, 1, 9], dtype=int32)

Is there a way to get just a=[2 3 1 9] from {a=} f-string as in the standard formatting in the first line?


Solution

  • By default, = f-string syntax calls repr on the thing to be formatted, since that's usually more useful than str or format for the debugging use cases the = syntax was designed for.

    You can have it apply normal formatting logic instead by specifying a format - even an empty format will do, so this would work:

    print(f'{a=:}')
    

    or you can explicitly say to call str with !s:

    print(f'{a=!s}')