Python numpy.array2string() Examples

The following are 30 code examples for showing how to use numpy.array2string(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: modelforge   Author: src-d   File: slogging.py    License: Apache License 2.0 6 votes vote down vote up
def getMessage(self):
        """
        Return the message for this LogRecord.

        Return the message for this LogRecord after merging any user-supplied \
        arguments with the message.
        """
        if isinstance(self.msg, numpy.ndarray):
            msg = self.array2string(self.msg)
        else:
            msg = str(self.msg)
        if self.args:
            a2s = self.array2string
            if isinstance(self.args, Dict):
                args = {k: (a2s(v) if isinstance(v, numpy.ndarray) else v)
                        for (k, v) in self.args.items()}
            elif isinstance(self.args, Sequence):
                args = tuple((a2s(a) if isinstance(a, numpy.ndarray) else a)
                             for a in self.args)
            else:
                raise TypeError("Unexpected input '%s' with type '%s'" % (self.args,
                                                                          type(self.args)))
            msg = msg % args
        return msg 
Example 2
Project: recruit   Author: Frank-qlu   File: arrayprint.py    License: Apache License 2.0 6 votes vote down vote up
def _array_str_implementation(
        a, max_line_width=None, precision=None, suppress_small=None,
        array2string=array2string):
    """Internal version of array_str() that allows overriding array2string."""
    if (_format_options['legacy'] == '1.13' and
            a.shape == () and not a.dtype.names):
        return str(a.item())

    # the str of 0d arrays is a special case: It should appear like a scalar,
    # so floats are not truncated by `precision`, and strings are not wrapped
    # in quotes. So we return the str of the scalar value.
    if a.shape == ():
        # obtain a scalar and call str on it, avoiding problems for subclasses
        # for which indexing with () returns a 0d instead of a scalar by using
        # ndarray's getindex. Also guard against recursive 0d object arrays.
        return _guarded_str(np.ndarray.__getitem__(a, ()))

    return array2string(a, max_line_width, precision, suppress_small, ' ', "") 
Example 3
Project: signaltrain   Author: drscotthawley   File: viz.py    License: GNU General Public License v3.0 6 votes vote down vote up
def set_knobs():
    global knob_names, knobs_nn
    setstr = 'global knobs_nn;  knobs_nn = np.array(['
    num_knobs = len(knob_names)
    for i in range(len(knob_names)):
        knob_name = knob_names[i]
        setstr += f"{knob_name}"
        if i < num_knobs-1: setstr += ','
    setstr += '])'
    #print('setstr = ',setstr)
    exec(setstr)
    #knobs_wc = knobs_nn * ()
    knobs_wc = knob_ranges[:,0] + (knobs_nn+0.5)*(knob_ranges[:,1]-knob_ranges[:,0])

    text = "knobs_wc = "+np.array2string(knobs_wc, precision=3, separator=',',suppress_small=True)
    cv2.rectangle(logo, (0, 0), (500, 25), (255,255,255), -1)
    cv2.putText(logo, text, (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0,0,0), lineType=cv2.LINE_AA)
    cv2.imshow(knob_controls_window, logo) 
Example 4
Project: D-VAE   Author: muhanzhang   File: formatting.py    License: MIT License 6 votes vote down vote up
def var_label(var, precision=3):
    """Return label of variable node."""
    if var.name is not None:
        return var.name
    elif isinstance(var, gof.Constant):
        h = np.asarray(var.data)
        is_const = False
        if h.ndim == 0:
            is_const = True
            h = np.array([h])
        dstr = np.array2string(h, precision=precision)
        if '\n' in dstr:
            dstr = dstr[:dstr.index('\n')]
        if is_const:
            dstr = dstr.replace('[', '').replace(']', '')
        return dstr
    else:
        return type_to_str(var.type) 
Example 5
Project: helen   Author: kishwarshafin   File: dataloader_debug.py    License: MIT License 6 votes vote down vote up
def __getitem__(self, index):
        """
        This method returns a single object. Dataloader uses this method to load images and then minibatches the loaded
        images
        :param index: Index indicating which image from all_images to be loaded
        :return: image and their auxiliary information
        """
        hdf5_filepath, image_name = self.all_images[index]

        # load all the information we need to save in the prediction hdf5
        with h5py.File(hdf5_filepath, 'r') as hdf5_file:
            contig = np.array2string(hdf5_file['images'][image_name]['contig'][()][0].astype(np.str)).replace("'", '')
            contig_start = hdf5_file['images'][image_name]['contig_start'][()][0].astype(np.int)
            contig_end = hdf5_file['images'][image_name]['contig_end'][()][0].astype(np.int)
            chunk_id = hdf5_file['images'][image_name]['feature_chunk_idx'][()][0].astype(np.int)
            image = hdf5_file['images'][image_name]['image'][()].astype(np.uint8)
            position = hdf5_file['images'][image_name]['position'][()].astype(np.int)
            label_base = hdf5_file['images'][image_name]['label_base'][()]
            label_run_length = hdf5_file['images'][image_name]['label_run_length'][()]

        return image, label_base, label_run_length, position, contig, contig_start, contig_end, chunk_id, hdf5_filepath 
Example 6
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: arrayprint.py    License: MIT License 6 votes vote down vote up
def _array_str_implementation(
        a, max_line_width=None, precision=None, suppress_small=None,
        array2string=array2string):
    """Internal version of array_str() that allows overriding array2string."""
    if (_format_options['legacy'] == '1.13' and
            a.shape == () and not a.dtype.names):
        return str(a.item())

    # the str of 0d arrays is a special case: It should appear like a scalar,
    # so floats are not truncated by `precision`, and strings are not wrapped
    # in quotes. So we return the str of the scalar value.
    if a.shape == ():
        # obtain a scalar and call str on it, avoiding problems for subclasses
        # for which indexing with () returns a 0d instead of a scalar by using
        # ndarray's getindex. Also guard against recursive 0d object arrays.
        return _guarded_str(np.ndarray.__getitem__(a, ()))

    return array2string(a, max_line_width, precision, suppress_small, ' ', "") 
Example 7
Project: chainer   Author: chainer   File: variable.py    License: MIT License 6 votes vote down vote up
def variable_repr(var):
    """Return the string representation of a variable.

    Args:
        var (~chainer.Variable): Input Variable.
    .. seealso:: numpy.array_repr
    """
    arr = _cpu._to_cpu(var.array)

    if var.name:
        prefix = 'variable ' + var.name
    else:
        prefix = 'variable'

    if arr is None:
        lst = 'None'
    elif arr.size > 0 or arr.shape == (0,):
        lst = numpy.array2string(arr, None, None, None, ', ', prefix + '(')
    else:  # show zero-length shape unless it is (0,)
        lst = '[], shape=%s' % (repr(arr.shape),)

    return '%s(%s)' % (prefix, lst) 
Example 8
Project: chainer   Author: chainer   File: variable.py    License: MIT License 6 votes vote down vote up
def variable_str(var):
    """Return the string representation of a variable.

    Args:
        var (~chainer.Variable): Input Variable.
    .. seealso:: numpy.array_str
    """
    arr = _cpu._to_cpu(var.array)

    if var.name:
        prefix = 'variable ' + var.name
    else:
        prefix = 'variable'

    if arr is None:
        lst = 'None'
    else:
        lst = numpy.array2string(arr, None, None, None, ' ', prefix + '(')

    return '%s(%s)' % (prefix, lst) 
Example 9
Project: imgcomp-cvpr   Author: fab-jul   File: logger.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, wrapper_str='{}', max_elements=None, precision=3, sep=','):
            self._array2string = lambda _arr: wrapper_str.format(
                    np.array2string(
                            _arr.flatten()[:max_elements],
                            precision=precision, separator=sep)) 
Example 10
Project: modelforge   Author: src-d   File: slogging.py    License: Apache License 2.0 5 votes vote down vote up
def array2string(arr: numpy.ndarray) -> str:
        """Format numpy array as a string."""
        shape = str(arr.shape)[1:-1]
        if shape.endswith(","):
            shape = shape[:-1]
        return numpy.array2string(arr, threshold=11) + "%s[%s]" % (arr.dtype, shape) 
Example 11
Project: recruit   Author: Frank-qlu   File: arrayprint.py    License: Apache License 2.0 5 votes vote down vote up
def array_str(a, max_line_width=None, precision=None, suppress_small=None):
    """
    Return a string representation of the data in an array.

    The data in the array is returned as a single string.  This function is
    similar to `array_repr`, the difference being that `array_repr` also
    returns information on the kind of array and its data type.

    Parameters
    ----------
    a : ndarray
        Input array.
    max_line_width : int, optional
        Inserts newlines if text is longer than `max_line_width`.  The
        default is, indirectly, 75.
    precision : int, optional
        Floating point precision.  Default is the current printing precision
        (usually 8), which can be altered using `set_printoptions`.
    suppress_small : bool, optional
        Represent numbers "very close" to zero as zero; default is False.
        Very close is defined by precision: if the precision is 8, e.g.,
        numbers smaller (in absolute value) than 5e-9 are represented as
        zero.

    See Also
    --------
    array2string, array_repr, set_printoptions

    Examples
    --------
    >>> np.array_str(np.arange(3))
    '[0 1 2]'

    """
    return _array_str_implementation(
        a, max_line_width, precision, suppress_small)


# needed if __array_function__ is disabled 
Example 12
Project: recruit   Author: Frank-qlu   File: test_arrayprint.py    License: Apache License 2.0 5 votes vote down vote up
def test_unexpected_kwarg(self):
        # ensure than an appropriate TypeError
        # is raised when array2string receives
        # an unexpected kwarg

        with assert_raises_regex(TypeError, 'nonsense'):
            np.array2string(np.array([1, 2, 3]),
                            nonsense=None) 
Example 13
Project: recruit   Author: Frank-qlu   File: test_arrayprint.py    License: Apache License 2.0 5 votes vote down vote up
def test_edgeitems_kwarg(self):
        # previously the global print options would be taken over the kwarg
        arr = np.zeros(3, int)
        assert_equal(
            np.array2string(arr, edgeitems=1, threshold=0),
            "[0 ... 0]"
        ) 
Example 14
Project: recruit   Author: Frank-qlu   File: test_arrayprint.py    License: Apache License 2.0 5 votes vote down vote up
def test_linewidth(self):
        a = np.full(6, 1)

        def make_str(a, width, **kw):
            return np.array2string(a, separator="", max_line_width=width, **kw)

        assert_equal(make_str(a, 8, legacy='1.13'), '[111111]')
        assert_equal(make_str(a, 7, legacy='1.13'), '[111111]')
        assert_equal(make_str(a, 5, legacy='1.13'), '[1111\n'
                                                    ' 11]')

        assert_equal(make_str(a, 8), '[111111]')
        assert_equal(make_str(a, 7), '[11111\n'
                                     ' 1]')
        assert_equal(make_str(a, 5), '[111\n'
                                     ' 111]')

        b = a[None,None,:]

        assert_equal(make_str(b, 12, legacy='1.13'), '[[[111111]]]')
        assert_equal(make_str(b,  9, legacy='1.13'), '[[[111111]]]')
        assert_equal(make_str(b,  8, legacy='1.13'), '[[[11111\n'
                                                     '   1]]]')

        assert_equal(make_str(b, 12), '[[[111111]]]')
        assert_equal(make_str(b,  9), '[[[111\n'
                                      '   111]]]')
        assert_equal(make_str(b,  8), '[[[11\n'
                                      '   11\n'
                                      '   11]]]') 
Example 15
Project: recruit   Author: Frank-qlu   File: test_arrayprint.py    License: Apache License 2.0 5 votes vote down vote up
def test_refcount(self):
        # make sure we do not hold references to the array due to a recursive
        # closure (gh-10620)
        gc.disable()
        a = np.arange(2)
        r1 = sys.getrefcount(a)
        np.array2string(a)
        np.array2string(a)
        r2 = sys.getrefcount(a)
        gc.collect()
        gc.enable()
        assert_(r1 == r2) 
Example 16
Project: recruit   Author: Frank-qlu   File: test_arrayprint.py    License: Apache License 2.0 5 votes vote down vote up
def test_0d_arrays(self):
        unicode = type(u'')

        assert_equal(unicode(np.array(u'café', '<U4')), u'café')

        if sys.version_info[0] >= 3:
            assert_equal(repr(np.array('café', '<U4')),
                         "array('café', dtype='<U4')")
        else:
            assert_equal(repr(np.array(u'café', '<U4')),
                         "array(u'caf\\xe9', dtype='<U4')")
        assert_equal(str(np.array('test', np.str_)), 'test')

        a = np.zeros(1, dtype=[('a', '<i4', (3,))])
        assert_equal(str(a[0]), '([0, 0, 0],)')

        assert_equal(repr(np.datetime64('2005-02-25')[...]),
                     "array('2005-02-25', dtype='datetime64[D]')")

        assert_equal(repr(np.timedelta64('10', 'Y')[...]),
                     "array(10, dtype='timedelta64[Y]')")

        # repr of 0d arrays is affected by printoptions
        x = np.array(1)
        np.set_printoptions(formatter={'all':lambda x: "test"})
        assert_equal(repr(x), "array(test)")
        # str is unaffected
        assert_equal(str(x), "1")

        # check `style` arg raises
        assert_warns(DeprecationWarning, np.array2string,
                                         np.array(1.), style=repr)
        # but not in legacy mode
        np.array2string(np.array(1.), style=repr, legacy='1.13')
        # gh-10934 style was broken in legacy mode, check it works
        np.array2string(np.array(1.), legacy='1.13') 
Example 17
Project: recruit   Author: Frank-qlu   File: test_datetime.py    License: Apache License 2.0 5 votes vote down vote up
def test_datetime_array_str(self):
        a = np.array(['2011-03-16', '1920-01-01', '2013-05-19'], dtype='M')
        assert_equal(str(a), "['2011-03-16' '1920-01-01' '2013-05-19']")

        a = np.array(['2011-03-16T13:55', '1920-01-01T03:12'], dtype='M')
        assert_equal(np.array2string(a, separator=', ',
                    formatter={'datetime': lambda x:
                            "'%s'" % np.datetime_as_string(x, timezone='UTC')}),
                     "['2011-03-16T13:55Z', '1920-01-01T03:12Z']")

        # Check that one NaT doesn't corrupt subsequent entries
        a = np.array(['2010', 'NaT', '2030']).astype('M')
        assert_equal(str(a), "['2010'  'NaT' '2030']") 
Example 18
Project: deepchem   Author: deepchem   File: datasets.py    License: MIT License 5 votes vote down vote up
def __repr__(self):
    """Convert self to REPL print representation."""
    threshold = dc.utils.get_print_threshold()
    task_str = np.array2string(
        np.array(self.get_task_names()), threshold=threshold)
    if self.__len__() < dc.utils.get_max_print_size():
      id_str = np.array2string(self.ids, threshold=threshold)
      return "<%s X.shape: %s, y.shape: %s, w.shape: %s, ids: %s, task_names: %s>" % (
          self.__class__.__name__, str(self.X.shape), str(self.y.shape),
          str(self.w.shape), id_str, task_str)
    else:
      return "<%s X.shape: %s, y.shape: %s, w.shape: %s, task_names: %s>" % (
          self.__class__.__name__, str(self.X.shape), str(self.y.shape),
          str(self.w.shape), task_str) 
Example 19
Project: AIX360   Author: IBM   File: classifiers.py    License: Apache License 2.0 5 votes vote down vote up
def predict_long(self, x):
        prob = self.predict(x)
        predicted_class = np.argmax(prob)
        prob_str = np.array2string(prob).replace('\n','')
        return(prob, predicted_class, prob_str) 
Example 20
Project: AIX360   Author: IBM   File: CEM_MAF_aen_PP.py    License: Apache License 2.0 5 votes vote down vote up
def generate_PP(self, img_mask, orig_img, orig_class, model, mask_size, mask_mat):
        def model_prediction(model, inputs):
            prob = model.model.predict(inputs)
            predicted_class = np.argmax(prob)
            prob_str = np.array2string(prob).replace('\n','')
            return prob, predicted_class, prob_str        # ranking

        success = False
        print("Start ranking:")
        mask_vec = img_mask.reshape(-1)
        sort_idx = np.argsort(mask_vec)
        total_nonezero = len(np.argsort(mask_vec>0))
        working_mask = np.zeros((1,) + (mask_size, mask_size) + (1,))
        for i in range(1,total_nonezero):
            temp_index = sort_idx[-i]
            mask_position = np.argwhere(mask_mat[temp_index]==1)
            for index in mask_position:
                working_mask[(0,) + tuple(index) + (0,)] = 1
            adv_img = working_mask * orig_img
            img_prob, img_class, img_prob_str = model_prediction(model, adv_img)
            print("i:{}, index:{}, value:{}, class:{}".format(i, temp_index, mask_vec[temp_index], img_class))
            if img_class == orig_class:
                success = True
                break
                
        return adv_img, success 
Example 21
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_arrayprint.py    License: MIT License 5 votes vote down vote up
def test_basic(self):
        """Basic test of array2string."""
        a = np.arange(3)
        assert_(np.array2string(a) == '[0 1 2]')
        assert_(np.array2string(a, max_line_width=4) == '[0 1\n 2]') 
Example 22
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_arrayprint.py    License: MIT License 5 votes vote down vote up
def test_style_keyword(self):
        """This should only apply to 0-D arrays. See #1218."""
        stylestr = np.array2string(np.array(1.5),
                                   style=lambda x: "Value in 0-D array: " + str(x))
        assert_(stylestr == 'Value in 0-D array: 1.5') 
Example 23
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_arrayprint.py    License: MIT License 5 votes vote down vote up
def test_format_function(self):
        """Test custom format function for each element in array."""
        def _format_function(x):
            if np.abs(x) < 1:
                return '.'
            elif np.abs(x) < 2:
                return 'o'
            else:
                return 'O'

        x = np.arange(3)
        if sys.version_info[0] >= 3:
            x_hex = "[0x0 0x1 0x2]"
            x_oct = "[0o0 0o1 0o2]"
        else:
            x_hex = "[0x0L 0x1L 0x2L]"
            x_oct = "[0L 01L 02L]"
        assert_(np.array2string(x, formatter={'all':_format_function}) ==
                "[. o O]")
        assert_(np.array2string(x, formatter={'int_kind':_format_function}) ==
                "[. o O]")
        assert_(np.array2string(x, formatter={'all':lambda x: "%.4f" % x}) ==
                "[0.0000 1.0000 2.0000]")
        assert_equal(np.array2string(x, formatter={'int':lambda x: hex(x)}),
                x_hex)
        assert_equal(np.array2string(x, formatter={'int':lambda x: oct(x)}),
                x_oct)

        x = np.arange(3.)
        assert_(np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x}) ==
                "[0.00 1.00 2.00]")
        assert_(np.array2string(x, formatter={'float':lambda x: "%.2f" % x}) ==
                "[0.00 1.00 2.00]")

        s = np.array(['abc', 'def'])
        assert_(np.array2string(s, formatter={'numpystr':lambda s: s*2}) ==
                '[abcabc defdef]') 
Example 24
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_datetime.py    License: MIT License 5 votes vote down vote up
def test_datetime_array_str(self):
        a = np.array(['2011-03-16', '1920-01-01', '2013-05-19'], dtype='M')
        assert_equal(str(a), "['2011-03-16' '1920-01-01' '2013-05-19']")

        a = np.array(['2011-03-16T13:55', '1920-01-01T03:12'], dtype='M')
        assert_equal(np.array2string(a, separator=', ',
                    formatter={'datetime': lambda x:
                            "'%s'" % np.datetime_as_string(x, timezone='UTC')}),
                     "['2011-03-16T13:55Z', '1920-01-01T03:12Z']")

        # Check that one NaT doesn't corrupt subsequent entries
        a = np.array(['2010', 'NaT', '2030']).astype('M')
        assert_equal(str(a), "['2010' 'NaT' '2030']") 
Example 25
Project: hazymaze   Author: guille0   File: build_the_maze.py    License: Apache License 2.0 5 votes vote down vote up
def build_maze(self, items, key=None):
        game = Master.instance()

        # Making a binary maze (1 is wall 0 is walkable)
        self.build_basic_maze()
        self.build_items(items)

        # Turn out binary maze into a string
        # Save it in a dictionary that points to the finished maze (self.case_array)
        # So if we are trying to build the same maze, we don't have to recreate it
        np.set_printoptions(threshold=np.inf)
        binary_maze_string = np.array2string(self.maze_array)

        if binary_maze_string in game.built_mazes.keys():
            self.case_array, self.entrances, self.items = game.built_mazes[binary_maze_string]
        else:
            self.compress_maze(items)
            game.built_mazes[binary_maze_string] = (self.case_array, self.entrances, self.items)

        if key is not None:
            if key == ord('q'):
                print(binary_maze_string)
                for e in self.entrances:
                    print(self.real_position(e[0], e[1]))
                print(self.entrances)
                print(self.items) 
Example 26
Project: vnpy_crypto   Author: birforce   File: test_arrayprint.py    License: MIT License 5 votes vote down vote up
def test_basic(self):
        """Basic test of array2string."""
        a = np.arange(3)
        assert_(np.array2string(a) == '[0 1 2]')
        assert_(np.array2string(a, max_line_width=4, legacy='1.13') == '[0 1\n 2]')
        assert_(np.array2string(a, max_line_width=4) == '[0\n 1\n 2]') 
Example 27
Project: vnpy_crypto   Author: birforce   File: test_arrayprint.py    License: MIT License 5 votes vote down vote up
def test_linewidth(self):
        a = np.full(6, 1)

        def make_str(a, width, **kw):
            return np.array2string(a, separator="", max_line_width=width, **kw)

        assert_equal(make_str(a, 8, legacy='1.13'), '[111111]')
        assert_equal(make_str(a, 7, legacy='1.13'), '[111111]')
        assert_equal(make_str(a, 5, legacy='1.13'), '[1111\n'
                                                    ' 11]')

        assert_equal(make_str(a, 8), '[111111]')
        assert_equal(make_str(a, 7), '[11111\n'
                                     ' 1]')
        assert_equal(make_str(a, 5), '[111\n'
                                     ' 111]')

        b = a[None,None,:]

        assert_equal(make_str(b, 12, legacy='1.13'), '[[[111111]]]')
        assert_equal(make_str(b,  9, legacy='1.13'), '[[[111111]]]')
        assert_equal(make_str(b,  8, legacy='1.13'), '[[[11111\n'
                                                     '   1]]]')

        assert_equal(make_str(b, 12), '[[[111111]]]')
        assert_equal(make_str(b,  9), '[[[111\n'
                                      '   111]]]')
        assert_equal(make_str(b,  8), '[[[11\n'
                                      '   11\n'
                                      '   11]]]') 
Example 28
Project: vnpy_crypto   Author: birforce   File: test_arrayprint.py    License: MIT License 5 votes vote down vote up
def test_wide_element(self):
        a = np.array(['xxxxx'])
        assert_equal(
            np.array2string(a, max_line_width=5),
            "['xxxxx']"
        )
        assert_equal(
            np.array2string(a, max_line_width=5, legacy='1.13'),
            "[ 'xxxxx']"
        ) 
Example 29
Project: vnpy_crypto   Author: birforce   File: test_arrayprint.py    License: MIT License 5 votes vote down vote up
def test_refcount(self):
        # make sure we do not hold references to the array due to a recursive
        # closure (gh-10620)
        gc.disable()
        a = np.arange(2)
        r1 = sys.getrefcount(a)
        np.array2string(a)
        np.array2string(a)
        r2 = sys.getrefcount(a)
        gc.collect()
        gc.enable()
        assert_(r1 == r2) 
Example 30
Project: vnpy_crypto   Author: birforce   File: test_arrayprint.py    License: MIT License 5 votes vote down vote up
def test_0d_arrays(self):
        unicode = type(u'')

        assert_equal(unicode(np.array(u'café', '<U4')), u'café')

        if sys.version_info[0] >= 3:
            assert_equal(repr(np.array('café', '<U4')),
                         "array('café', dtype='<U4')")
        else:
            assert_equal(repr(np.array(u'café', '<U4')),
                         "array(u'caf\\xe9', dtype='<U4')")
        assert_equal(str(np.array('test', np.str_)), 'test')

        a = np.zeros(1, dtype=[('a', '<i4', (3,))])
        assert_equal(str(a[0]), '([0, 0, 0],)')

        assert_equal(repr(np.datetime64('2005-02-25')[...]),
                     "array('2005-02-25', dtype='datetime64[D]')")

        assert_equal(repr(np.timedelta64('10', 'Y')[...]),
                     "array(10, dtype='timedelta64[Y]')")

        # repr of 0d arrays is affected by printoptions
        x = np.array(1)
        np.set_printoptions(formatter={'all':lambda x: "test"})
        assert_equal(repr(x), "array(test)")
        # str is unaffected
        assert_equal(str(x), "1")

        # check `style` arg raises
        assert_warns(DeprecationWarning, np.array2string,
                                         np.array(1.), style=repr)
        # but not in legacy mode
        np.array2string(np.array(1.), style=repr, legacy='1.13')
        # gh-10934 style was broken in legacy mode, check it works
        np.array2string(np.array(1.), legacy='1.13')