Return a copy of `a` with its elements centered in a string of length `width`. Parameters ---------- a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype width : array_like, with any integer dtype The length of the resulting strings, unless ``width <
(a, width, fillchar=' ')
| 691 | @set_module("numpy.strings") |
| 692 | @array_function_dispatch(_just_dispatcher) |
| 693 | def center(a, width, fillchar=' '): |
| 694 | """ |
| 695 | Return a copy of `a` with its elements centered in a string of |
| 696 | length `width`. |
| 697 | |
| 698 | Parameters |
| 699 | ---------- |
| 700 | a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype |
| 701 | |
| 702 | width : array_like, with any integer dtype |
| 703 | The length of the resulting strings, unless ``width < str_len(a)``. |
| 704 | fillchar : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype |
| 705 | Optional padding character to use (default is space). |
| 706 | |
| 707 | Returns |
| 708 | ------- |
| 709 | out : ndarray |
| 710 | Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype, |
| 711 | depending on input types |
| 712 | |
| 713 | See Also |
| 714 | -------- |
| 715 | str.center |
| 716 | |
| 717 | Notes |
| 718 | ----- |
| 719 | While it is possible for ``a`` and ``fillchar`` to have different dtypes, |
| 720 | passing a non-ASCII character in ``fillchar`` when ``a`` is of dtype "S" |
| 721 | is not allowed, and a ``ValueError`` is raised. |
| 722 | |
| 723 | Examples |
| 724 | -------- |
| 725 | >>> import numpy as np |
| 726 | >>> c = np.array(['a1b2','1b2a','b2a1','2a1b']); c |
| 727 | array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='<U4') |
| 728 | >>> np.strings.center(c, width=9) |
| 729 | array([' a1b2 ', ' 1b2a ', ' b2a1 ', ' 2a1b '], dtype='<U9') |
| 730 | >>> np.strings.center(c, width=9, fillchar='*') |
| 731 | array(['***a1b2**', '***1b2a**', '***b2a1**', '***2a1b**'], dtype='<U9') |
| 732 | >>> np.strings.center(c, width=1) |
| 733 | array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='<U4') |
| 734 | |
| 735 | """ |
| 736 | width = np.asanyarray(width) |
| 737 | |
| 738 | if not np.issubdtype(width.dtype, np.integer): |
| 739 | raise TypeError(f"unsupported type {width.dtype} for operand 'width'") |
| 740 | |
| 741 | a = np.asanyarray(a) |
| 742 | fillchar = np.asanyarray(fillchar) |
| 743 | |
| 744 | if np.any(str_len(fillchar) != 1): |
| 745 | raise TypeError( |
| 746 | "The fill character must be exactly one character long") |
| 747 | |
| 748 | if np.result_type(a, fillchar).char == "T": |
| 749 | return _center(a, width, fillchar) |
| 750 |