/
strings.py
1498 lines (1174 loc) · 40.5 KB
/
strings.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
This module contains a set of functions for vectorized string
operations.
"""
import sys
import numpy as np
from numpy import (
equal, not_equal, less, less_equal, greater, greater_equal,
add, multiply as _multiply_ufunc,
)
from numpy._core.multiarray import _vec_string
from numpy._core.umath import (
isalpha,
isdigit,
isspace,
isalnum,
islower,
isupper,
istitle,
isdecimal,
isnumeric,
str_len,
find as _find_ufunc,
rfind as _rfind_ufunc,
index as _index_ufunc,
rindex as _rindex_ufunc,
count as _count_ufunc,
startswith as _startswith_ufunc,
endswith as _endswith_ufunc,
_lstrip_whitespace,
_lstrip_chars,
_rstrip_whitespace,
_rstrip_chars,
_strip_whitespace,
_strip_chars,
_replace,
_expandtabs_length,
_expandtabs,
_center,
_ljust,
_rjust,
_zfill,
_partition,
_partition_index,
_rpartition,
_rpartition_index,
)
__all__ = [
# UFuncs
"equal", "not_equal", "less", "less_equal", "greater", "greater_equal",
"add", "multiply", "isalpha", "isdigit", "isspace", "isalnum", "islower",
"isupper", "istitle", "isdecimal", "isnumeric", "str_len", "find",
"rfind", "index", "rindex", "count", "startswith", "endswith", "lstrip",
"rstrip", "strip", "replace", "expandtabs", "center", "ljust", "rjust",
"zfill", "partition", "rpartition",
# _vec_string - Will gradually become ufuncs as well
"upper", "lower", "swapcase", "capitalize", "title",
# _vec_string - Will probably not become ufuncs
"mod", "decode", "encode", "translate",
# Removed from namespace until behavior has been crystalized
# "join", "split", "rsplit", "splitlines",
]
MAX = np.iinfo(np.int64).max
def _get_num_chars(a):
"""
Helper function that returns the number of characters per field in
a string or unicode array. This is to abstract out the fact that
for a unicode array this is itemsize / 4.
"""
if issubclass(a.dtype.type, np.str_):
return a.itemsize // 4
return a.itemsize
def _to_bytes_or_str_array(result, output_dtype_like):
"""
Helper function to cast a result back into an array
with the appropriate dtype if an object array must be used
as an intermediary.
"""
output_dtype_like = np.asarray(output_dtype_like)
if result.size == 0:
# Calling asarray & tolist in an empty array would result
# in losing shape information
return result.astype(output_dtype_like.dtype)
ret = np.asarray(result.tolist())
if isinstance(output_dtype_like.dtype, np.dtypes.StringDType):
return ret.astype(type(output_dtype_like.dtype))
return ret.astype(type(output_dtype_like.dtype)(_get_num_chars(ret)))
def _clean_args(*args):
"""
Helper function for delegating arguments to Python string
functions.
Many of the Python string operations that have optional arguments
do not use 'None' to indicate a default value. In these cases,
we need to remove all None arguments, and those following them.
"""
newargs = []
for chk in args:
if chk is None:
break
newargs.append(chk)
return newargs
def multiply(a, i):
"""
Return (a * i), that is string multiple concatenation,
element-wise.
Values in ``i`` of less than 0 are treated as 0 (which yields an
empty string).
Parameters
----------
a : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype
i : array_like, with any integer dtype
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
Examples
--------
>>> a = np.array(["a", "b", "c"])
>>> np.strings.multiply(a, 3)
array(['aaa', 'bbb', 'ccc'], dtype='<U3')
>>> i = np.array([1, 2, 3])
>>> np.strings.multiply(a, i)
array(['a', 'bb', 'ccc'], dtype='<U3')
>>> np.strings.multiply(np.array(['a']), i)
array(['a', 'aa', 'aaa'], dtype='<U3')
>>> a = np.array(['a', 'b', 'c', 'd', 'e', 'f']).reshape((2, 3))
>>> np.strings.multiply(a, 3)
array([['aaa', 'bbb', 'ccc'],
['ddd', 'eee', 'fff']], dtype='<U3')
>>> np.strings.multiply(a, i)
array([['a', 'bb', 'ccc'],
['d', 'ee', 'fff']], dtype='<U3')
"""
a = np.asanyarray(a)
i = np.asanyarray(i)
if not np.issubdtype(i.dtype, np.integer):
raise TypeError(f"unsupported type {i.dtype} for operand 'i'")
i = np.maximum(i, 0)
# delegate to stringdtype loops that also do overflow checking
if a.dtype.char == "T":
return a * i
a_len = str_len(a)
# Ensure we can do a_len * i without overflow.
if np.any(a_len > sys.maxsize / np.maximum(i, 1)):
raise MemoryError("repeated string is too long")
buffersizes = a_len * i
out_dtype = f"{a.dtype.char}{buffersizes.max()}"
out = np.empty_like(a, shape=buffersizes.shape, dtype=out_dtype)
return _multiply_ufunc(a, i, out=out)
def mod(a, values):
"""
Return (a % i), that is pre-Python 2.6 string formatting
(interpolation), element-wise for a pair of array_likes of str
or unicode.
Parameters
----------
a : array_like, with `np.bytes_` or `np.str_` dtype
values : array_like of values
These values will be element-wise interpolated into the string.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
"""
return _to_bytes_or_str_array(
_vec_string(a, np.object_, '__mod__', (values,)), a)
def find(a, sub, start=0, end=None):
"""
For each element, return the lowest index in the string where
substring ``sub`` is found, such that ``sub`` is contained in the
range [``start``, ``end``).
Parameters
----------
a : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype
sub : array_like, with `np.bytes_` or `np.str_` dtype
The substring to search for.
start, end : array_like, with any integer dtype
The range to look in, interpreted as in slice notation.
Returns
-------
y : ndarray
Output array of ints
See Also
--------
str.find
Examples
--------
>>> a = np.array(["NumPy is a Python library"])
>>> np.strings.find(a, "Python")
array([11])
"""
end = end if end is not None else MAX
return _find_ufunc(a, sub, start, end)
def rfind(a, sub, start=0, end=None):
"""
For each element, return the highest index in the string where
substring ``sub`` is found, such that ``sub`` is contained in the
range [``start``, ``end``).
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
sub : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
The substring to search for.
start, end : array_like, with any integer dtype
The range to look in, interpreted as in slice notation.
Returns
-------
y : ndarray
Output array of ints
See Also
--------
str.rfind
"""
end = end if end is not None else MAX
return _rfind_ufunc(a, sub, start, end)
def index(a, sub, start=0, end=None):
"""
Like `find`, but raises :exc:`ValueError` when the substring is not found.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
sub : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
start, end : array_like, with any integer dtype, optional
Returns
-------
out : ndarray
Output array of ints.
See Also
--------
find, str.index
Examples
--------
>>> a = np.array(["Computer Science"])
>>> np.strings.index(a, "Science", start=0, end=None)
array([9])
"""
end = end if end is not None else MAX
return _index_ufunc(a, sub, start, end)
def rindex(a, sub, start=0, end=None):
"""
Like `rfind`, but raises :exc:`ValueError` when the substring `sub` is
not found.
Parameters
----------
a : array-like, with `np.bytes_` or `np.str_` dtype
sub : array-like, with `np.bytes_` or `np.str_` dtype
start, end : array-like, with any integer dtype, optional
Returns
-------
out : ndarray
Output array of ints.
See Also
--------
rfind, str.rindex
Examples
--------
>>> a = np.array(["Computer Science"])
>>> np.strings.rindex(a, "Science", start=0, end=None)
array([9])
"""
end = end if end is not None else MAX
return _rindex_ufunc(a, sub, start, end)
def count(a, sub, start=0, end=None):
"""
Returns an array with the number of non-overlapping occurrences of
substring ``sub`` in the range [``start``, ``end``).
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
sub : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
The substring to search for.
start, end : array_like, with any integer dtype
The range to look in, interpreted as in slice notation.
Returns
-------
y : ndarray
Output array of ints
See Also
--------
str.count
Examples
--------
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> c
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
>>> np.strings.count(c, 'A')
array([3, 1, 1])
>>> np.strings.count(c, 'aA')
array([3, 1, 0])
>>> np.strings.count(c, 'A', start=1, end=4)
array([2, 1, 1])
>>> np.strings.count(c, 'A', start=1, end=3)
array([1, 0, 0])
"""
end = end if end is not None else MAX
return _count_ufunc(a, sub, start, end)
def startswith(a, prefix, start=0, end=None):
"""
Returns a boolean array which is `True` where the string element
in ``a`` starts with ``prefix``, otherwise `False`.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
prefix : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
start, end : array_like, with any integer dtype
With ``start``, test beginning at that position. With ``end``,
stop comparing at that position.
Returns
-------
out : ndarray
Output array of bools
See Also
--------
str.startswith
"""
end = end if end is not None else MAX
return _startswith_ufunc(a, prefix, start, end)
def endswith(a, suffix, start=0, end=None):
"""
Returns a boolean array which is `True` where the string element
in ``a`` ends with ``suffix``, otherwise `False`.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
suffix : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
start, end : array_like, with any integer dtype
With ``start``, test beginning at that position. With ``end``,
stop comparing at that position.
Returns
-------
out : ndarray
Output array of bools
See Also
--------
str.endswith
Examples
--------
>>> s = np.array(['foo', 'bar'])
>>> s
array(['foo', 'bar'], dtype='<U3')
>>> np.strings.endswith(s, 'ar')
array([False, True])
>>> np.strings.endswith(s, 'a', start=1, end=2)
array([False, True])
"""
end = end if end is not None else MAX
return _endswith_ufunc(a, suffix, start, end)
def decode(a, encoding=None, errors=None):
r"""
Calls :meth:`bytes.decode` element-wise.
The set of available codecs comes from the Python standard library,
and may be extended at runtime. For more information, see the
:mod:`codecs` module.
Parameters
----------
a : array_like, with ``bytes_`` dtype
encoding : str, optional
The name of an encoding
errors : str, optional
Specifies how to handle encoding errors
Returns
-------
out : ndarray
See Also
--------
:py:meth:`bytes.decode`
Notes
-----
The type of the result will depend on the encoding specified.
Examples
--------
>>> c = np.array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@',
... b'\x81\x82\xc2\xc1\xc2\x82\x81'])
>>> c
array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@',
b'\x81\x82\xc2\xc1\xc2\x82\x81'], dtype='|S7')
>>> np.strings.decode(c, encoding='cp037')
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
"""
return _to_bytes_or_str_array(
_vec_string(a, np.object_, 'decode', _clean_args(encoding, errors)),
np.str_(''))
def encode(a, encoding=None, errors=None):
"""
Calls :meth:`str.encode` element-wise.
The set of available codecs comes from the Python standard library,
and may be extended at runtime. For more information, see the
:mod:`codecs` module.
Parameters
----------
a : array_like, with ``StringDType`` or ``str_`` dtype
encoding : str, optional
The name of an encoding
errors : str, optional
Specifies how to handle encoding errors
Returns
-------
out : ndarray
See Also
--------
str.encode
Notes
-----
The type of the result will depend on the encoding specified.
Examples
--------
>>> a = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> np.strings.encode(a, encoding='cp037')
array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@',
b'\x81\x82\xc2\xc1\xc2\x82\x81'], dtype='|S7')
"""
return _to_bytes_or_str_array(
_vec_string(a, np.object_, 'encode', _clean_args(encoding, errors)),
np.bytes_(b''))
def expandtabs(a, tabsize=8):
"""
Return a copy of each string element where all tab characters are
replaced by one or more spaces.
Calls :meth:`str.expandtabs` element-wise.
Return a copy of each string element where all tab characters are
replaced by one or more spaces, depending on the current column
and the given `tabsize`. The column number is reset to zero after
each newline occurring in the string. This doesn't understand other
non-printing characters or escape sequences.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Input array
tabsize : int, optional
Replace tabs with `tabsize` number of spaces. If not given defaults
to 8 spaces.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input type
See Also
--------
str.expandtabs
Examples
--------
>>> a = np.array(['\t\tHello\tworld'])
>>> np.strings.expandtabs(a, tabsize=4) # doctest: +SKIP
array([' Hello world'], dtype='<U21') # doctest: +SKIP
"""
a = np.asanyarray(a)
tabsize = np.asanyarray(tabsize)
if a.dtype.char == "T":
return _expandtabs(a, tabsize)
buffersizes = _expandtabs_length(a, tabsize)
out_dtype = f"{a.dtype.char}{buffersizes.max()}"
out = np.empty_like(a, shape=buffersizes.shape, dtype=out_dtype)
return _expandtabs(a, tabsize, out=out)
def center(a, width, fillchar=' '):
"""
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 < str_len(a)``.
fillchar : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Optional padding character to use (default is space).
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.center
Notes
-----
While it is possible for ``a`` and ``fillchar`` to have different dtypes,
passing a non-ASCII character in ``fillchar`` when ``a`` is of dtype "S"
is not allowed, and a ``ValueError`` is raised.
Examples
--------
>>> c = np.array(['a1b2','1b2a','b2a1','2a1b']); c
array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='<U4')
>>> np.strings.center(c, width=9)
array([' a1b2 ', ' 1b2a ', ' b2a1 ', ' 2a1b '], dtype='<U9')
>>> np.strings.center(c, width=9, fillchar='*')
array(['***a1b2**', '***1b2a**', '***b2a1**', '***2a1b**'], dtype='<U9')
>>> np.strings.center(c, width=1)
array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='<U4')
"""
a = np.asanyarray(a)
width = np.maximum(str_len(a), width)
fillchar = np.asanyarray(fillchar, dtype=a.dtype)
if np.any(str_len(fillchar) != 1):
raise TypeError(
"The fill character must be exactly one character long")
if a.dtype.char == "T":
return _center(a, width, fillchar)
out_dtype = f"{a.dtype.char}{width.max()}"
shape = np.broadcast_shapes(a.shape, width.shape, fillchar.shape)
out = np.empty_like(a, shape=shape, dtype=out_dtype)
return _center(a, width, fillchar, out=out)
def ljust(a, width, fillchar=' '):
"""
Return an array with the elements of `a` left-justified 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 < str_len(a)``.
fillchar : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Optional character to use for padding (default is space).
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.ljust
Notes
-----
While it is possible for ``a`` and ``fillchar`` to have different dtypes,
passing a non-ASCII character in ``fillchar`` when ``a`` is of dtype "S"
is not allowed, and a ``ValueError`` is raised.
Examples
--------
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> np.strings.ljust(c, width=3)
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
>>> np.strings.ljust(c, width=9)
array(['aAaAaA ', ' aA ', 'abBABba '], dtype='<U9')
"""
a = np.asanyarray(a)
width = np.maximum(str_len(a), width)
fillchar = np.asanyarray(fillchar, dtype=a.dtype)
if np.any(str_len(fillchar) != 1):
raise TypeError(
"The fill character must be exactly one character long")
if a.dtype.char == "T":
return _ljust(a, width, fillchar)
shape = np.broadcast_shapes(a.shape, width.shape, fillchar.shape)
out_dtype = f"{a.dtype.char}{width.max()}"
out = np.empty_like(a, shape=shape, dtype=out_dtype)
return _ljust(a, width, fillchar, out=out)
def rjust(a, width, fillchar=' '):
"""
Return an array with the elements of `a` right-justified 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 < str_len(a)``.
fillchar : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Optional padding character to use (default is space).
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.rjust
Notes
-----
While it is possible for ``a`` and ``fillchar`` to have different dtypes,
passing a non-ASCII character in ``fillchar`` when ``a`` is of dtype "S"
is not allowed, and a ``ValueError`` is raised.
Examples
--------
>>> a = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> np.strings.rjust(a, width=3)
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
>>> np.strings.rjust(a, width=9)
array([' aAaAaA', ' aA ', ' abBABba'], dtype='<U9')
"""
a = np.asanyarray(a)
width = np.maximum(str_len(a), width)
fillchar = np.asanyarray(fillchar, dtype=a.dtype)
if np.any(str_len(fillchar) != 1):
raise TypeError(
"The fill character must be exactly one character long")
if a.dtype.char == "T":
return _rjust(a, width, fillchar)
shape = np.broadcast_shapes(a.shape, width.shape, fillchar.shape)
out_dtype = f"{a.dtype.char}{width.max()}"
out = np.empty_like(a, shape=shape, dtype=out_dtype)
return _rjust(a, width, fillchar, out=out)
def zfill(a, width):
"""
Return the numeric string left-filled with zeros. A leading
sign prefix (``+``/``-``) is handled by inserting the padding
after the sign character rather than before.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
width : array_like, with any integer dtype
Width of string to left-fill elements in `a`.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input type
See Also
--------
str.zfill
Examples
--------
>>> np.strings.zfill(['1', '-1', '+1'], 3)
array(['001', '-01', '+01'], dtype='<U3')
"""
a = np.asanyarray(a)
width = np.maximum(str_len(a), width)
if a.dtype.char == "T":
return _zfill(a, width)
shape = np.broadcast_shapes(a.shape, width.shape)
out_dtype = f"{a.dtype.char}{width.max()}"
out = np.empty_like(a, shape=shape, dtype=out_dtype)
return _zfill(a, width, out=out)
def lstrip(a, chars=None):
"""
For each element in `a`, return a copy with the leading characters
removed.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
chars : scalar with the same dtype as ``a``, optional
The ``chars`` argument is a string specifying the set of
characters to be removed. If ``None``, the ``chars``
argument defaults to removing whitespace. The ``chars`` argument
is not a prefix or suffix; rather, all combinations of its
values are stripped.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.lstrip
Examples
--------
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> c
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
# The 'a' variable is unstripped from c[1] because of leading whitespace.
>>> np.strings.lstrip(c, 'a')
array(['AaAaA', ' aA ', 'bBABba'], dtype='<U7')
>>> np.strings.lstrip(c, 'A') # leaves c unchanged
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
>>> (np.strings.lstrip(c, ' ') == np.strings.lstrip(c, '')).all()
np.False_
>>> (np.strings.lstrip(c, ' ') == np.strings.lstrip(c)).all()
np.True_
"""
if chars is None:
return _lstrip_whitespace(a)
return _lstrip_chars(a, chars)
def rstrip(a, chars=None):
"""
For each element in `a`, return a copy with the trailing characters
removed.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
chars : scalar with the same dtype as ``a``, optional
The ``chars`` argument is a string specifying the set of
characters to be removed. If ``None``, the ``chars``
argument defaults to removing whitespace. The ``chars`` argument
is not a prefix or suffix; rather, all combinations of its
values are stripped.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.rstrip
Examples
--------
>>> c = np.array(['aAaAaA', 'abBABba'])
>>> c
array(['aAaAaA', 'abBABba'], dtype='<U7')
>>> np.strings.rstrip(c, 'a')
array(['aAaAaA', 'abBABb'], dtype='<U7')
>>> np.strings.rstrip(c, 'A')
array(['aAaAa', 'abBABba'], dtype='<U7')
"""
if chars is None:
return _rstrip_whitespace(a)
return _rstrip_chars(a, chars)
def strip(a, chars=None):
"""
For each element in `a`, return a copy with the leading and
trailing characters removed.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
chars : scalar with the same dtype as ``a``, optional
The ``chars`` argument is a string specifying the set of
characters to be removed. If ``None``, the ``chars``
argument defaults to removing whitespace. The ``chars`` argument
is not a prefix or suffix; rather, all combinations of its
values are stripped.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.strip
Examples
--------
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> c
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
>>> np.strings.strip(c)
array(['aAaAaA', 'aA', 'abBABba'], dtype='<U7')
# 'a' unstripped from c[1] because of leading whitespace.
>>> np.strings.strip(c, 'a')
array(['AaAaA', ' aA ', 'bBABb'], dtype='<U7')
# 'A' unstripped from c[1] because of trailing whitespace.
>>> np.strings.strip(c, 'A')
array(['aAaAa', ' aA ', 'abBABba'], dtype='<U7')
"""
if chars is None:
return _strip_whitespace(a)
return _strip_chars(a, chars)
def upper(a):
"""
Return an array with the elements converted to uppercase.
Calls :meth:`str.upper` element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Input array.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.upper
Examples
--------
>>> c = np.array(['a1b c', '1bca', 'bca1']); c
array(['a1b c', '1bca', 'bca1'], dtype='<U5')
>>> np.strings.upper(c)
array(['A1B C', '1BCA', 'BCA1'], dtype='<U5')
"""
a_arr = np.asarray(a)
return _vec_string(a_arr, a_arr.dtype, 'upper')
def lower(a):
"""
Return an array with the elements converted to lowercase.
Call :meth:`str.lower` element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Input array.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.lower
Examples
--------
>>> c = np.array(['A1B C', '1BCA', 'BCA1']); c
array(['A1B C', '1BCA', 'BCA1'], dtype='<U5')
>>> np.strings.lower(c)
array(['a1b c', '1bca', 'bca1'], dtype='<U5')
"""
a_arr = np.asarray(a)
return _vec_string(a_arr, a_arr.dtype, 'lower')
def swapcase(a):