defchararray.py 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914
  1. """
  2. This module contains a set of functions for vectorized string
  3. operations and methods.
  4. .. note::
  5. The `chararray` class exists for backwards compatibility with
  6. Numarray, it is not recommended for new development. Starting from numpy
  7. 1.4, if one needs arrays of strings, it is recommended to use arrays of
  8. `dtype` `object_`, `bytes_` or `str_`, and use the free functions
  9. in the `numpy.char` module for fast vectorized string operations.
  10. Some methods will only be available if the corresponding string method is
  11. available in your version of Python.
  12. The preferred alias for `defchararray` is `numpy.char`.
  13. """
  14. import functools
  15. from .._utils import set_module
  16. from .numerictypes import (
  17. bytes_, str_, integer, int_, object_, bool_, character)
  18. from .numeric import ndarray, compare_chararrays
  19. from .numeric import array as narray
  20. from numpy.core.multiarray import _vec_string
  21. from numpy.core import overrides
  22. from numpy.compat import asbytes
  23. import numpy
  24. __all__ = [
  25. 'equal', 'not_equal', 'greater_equal', 'less_equal',
  26. 'greater', 'less', 'str_len', 'add', 'multiply', 'mod', 'capitalize',
  27. 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs',
  28. 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
  29. 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition',
  30. 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
  31. 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
  32. 'title', 'translate', 'upper', 'zfill', 'isnumeric', 'isdecimal',
  33. 'array', 'asarray'
  34. ]
  35. _globalvar = 0
  36. array_function_dispatch = functools.partial(
  37. overrides.array_function_dispatch, module='numpy.char')
  38. def _is_unicode(arr):
  39. """Returns True if arr is a string or a string array with a dtype that
  40. represents a unicode string, otherwise returns False.
  41. """
  42. if (isinstance(arr, str) or
  43. issubclass(numpy.asarray(arr).dtype.type, str)):
  44. return True
  45. return False
  46. def _to_bytes_or_str_array(result, output_dtype_like=None):
  47. """
  48. Helper function to cast a result back into an array
  49. with the appropriate dtype if an object array must be used
  50. as an intermediary.
  51. """
  52. ret = numpy.asarray(result.tolist())
  53. dtype = getattr(output_dtype_like, 'dtype', None)
  54. if dtype is not None:
  55. return ret.astype(type(dtype)(_get_num_chars(ret)), copy=False)
  56. return ret
  57. def _clean_args(*args):
  58. """
  59. Helper function for delegating arguments to Python string
  60. functions.
  61. Many of the Python string operations that have optional arguments
  62. do not use 'None' to indicate a default value. In these cases,
  63. we need to remove all None arguments, and those following them.
  64. """
  65. newargs = []
  66. for chk in args:
  67. if chk is None:
  68. break
  69. newargs.append(chk)
  70. return newargs
  71. def _get_num_chars(a):
  72. """
  73. Helper function that returns the number of characters per field in
  74. a string or unicode array. This is to abstract out the fact that
  75. for a unicode array this is itemsize / 4.
  76. """
  77. if issubclass(a.dtype.type, str_):
  78. return a.itemsize // 4
  79. return a.itemsize
  80. def _binary_op_dispatcher(x1, x2):
  81. return (x1, x2)
  82. @array_function_dispatch(_binary_op_dispatcher)
  83. def equal(x1, x2):
  84. """
  85. Return (x1 == x2) element-wise.
  86. Unlike `numpy.equal`, this comparison is performed by first
  87. stripping whitespace characters from the end of the string. This
  88. behavior is provided for backward-compatibility with numarray.
  89. Parameters
  90. ----------
  91. x1, x2 : array_like of str or unicode
  92. Input arrays of the same shape.
  93. Returns
  94. -------
  95. out : ndarray
  96. Output array of bools.
  97. See Also
  98. --------
  99. not_equal, greater_equal, less_equal, greater, less
  100. """
  101. return compare_chararrays(x1, x2, '==', True)
  102. @array_function_dispatch(_binary_op_dispatcher)
  103. def not_equal(x1, x2):
  104. """
  105. Return (x1 != x2) element-wise.
  106. Unlike `numpy.not_equal`, this comparison is performed by first
  107. stripping whitespace characters from the end of the string. This
  108. behavior is provided for backward-compatibility with numarray.
  109. Parameters
  110. ----------
  111. x1, x2 : array_like of str or unicode
  112. Input arrays of the same shape.
  113. Returns
  114. -------
  115. out : ndarray
  116. Output array of bools.
  117. See Also
  118. --------
  119. equal, greater_equal, less_equal, greater, less
  120. """
  121. return compare_chararrays(x1, x2, '!=', True)
  122. @array_function_dispatch(_binary_op_dispatcher)
  123. def greater_equal(x1, x2):
  124. """
  125. Return (x1 >= x2) element-wise.
  126. Unlike `numpy.greater_equal`, this comparison is performed by
  127. first stripping whitespace characters from the end of the string.
  128. This behavior is provided for backward-compatibility with
  129. numarray.
  130. Parameters
  131. ----------
  132. x1, x2 : array_like of str or unicode
  133. Input arrays of the same shape.
  134. Returns
  135. -------
  136. out : ndarray
  137. Output array of bools.
  138. See Also
  139. --------
  140. equal, not_equal, less_equal, greater, less
  141. """
  142. return compare_chararrays(x1, x2, '>=', True)
  143. @array_function_dispatch(_binary_op_dispatcher)
  144. def less_equal(x1, x2):
  145. """
  146. Return (x1 <= x2) element-wise.
  147. Unlike `numpy.less_equal`, this comparison is performed by first
  148. stripping whitespace characters from the end of the string. This
  149. behavior is provided for backward-compatibility with numarray.
  150. Parameters
  151. ----------
  152. x1, x2 : array_like of str or unicode
  153. Input arrays of the same shape.
  154. Returns
  155. -------
  156. out : ndarray
  157. Output array of bools.
  158. See Also
  159. --------
  160. equal, not_equal, greater_equal, greater, less
  161. """
  162. return compare_chararrays(x1, x2, '<=', True)
  163. @array_function_dispatch(_binary_op_dispatcher)
  164. def greater(x1, x2):
  165. """
  166. Return (x1 > x2) element-wise.
  167. Unlike `numpy.greater`, this comparison is performed by first
  168. stripping whitespace characters from the end of the string. This
  169. behavior is provided for backward-compatibility with numarray.
  170. Parameters
  171. ----------
  172. x1, x2 : array_like of str or unicode
  173. Input arrays of the same shape.
  174. Returns
  175. -------
  176. out : ndarray
  177. Output array of bools.
  178. See Also
  179. --------
  180. equal, not_equal, greater_equal, less_equal, less
  181. """
  182. return compare_chararrays(x1, x2, '>', True)
  183. @array_function_dispatch(_binary_op_dispatcher)
  184. def less(x1, x2):
  185. """
  186. Return (x1 < x2) element-wise.
  187. Unlike `numpy.greater`, this comparison is performed by first
  188. stripping whitespace characters from the end of the string. This
  189. behavior is provided for backward-compatibility with numarray.
  190. Parameters
  191. ----------
  192. x1, x2 : array_like of str or unicode
  193. Input arrays of the same shape.
  194. Returns
  195. -------
  196. out : ndarray
  197. Output array of bools.
  198. See Also
  199. --------
  200. equal, not_equal, greater_equal, less_equal, greater
  201. """
  202. return compare_chararrays(x1, x2, '<', True)
  203. def _unary_op_dispatcher(a):
  204. return (a,)
  205. @array_function_dispatch(_unary_op_dispatcher)
  206. def str_len(a):
  207. """
  208. Return len(a) element-wise.
  209. Parameters
  210. ----------
  211. a : array_like of str or unicode
  212. Returns
  213. -------
  214. out : ndarray
  215. Output array of integers
  216. See Also
  217. --------
  218. len
  219. Examples
  220. --------
  221. >>> a = np.array(['Grace Hopper Conference', 'Open Source Day'])
  222. >>> np.char.str_len(a)
  223. array([23, 15])
  224. >>> a = np.array([u'\u0420', u'\u043e'])
  225. >>> np.char.str_len(a)
  226. array([1, 1])
  227. >>> a = np.array([['hello', 'world'], [u'\u0420', u'\u043e']])
  228. >>> np.char.str_len(a)
  229. array([[5, 5], [1, 1]])
  230. """
  231. # Note: __len__, etc. currently return ints, which are not C-integers.
  232. # Generally intp would be expected for lengths, although int is sufficient
  233. # due to the dtype itemsize limitation.
  234. return _vec_string(a, int_, '__len__')
  235. @array_function_dispatch(_binary_op_dispatcher)
  236. def add(x1, x2):
  237. """
  238. Return element-wise string concatenation for two arrays of str or unicode.
  239. Arrays `x1` and `x2` must have the same shape.
  240. Parameters
  241. ----------
  242. x1 : array_like of str or unicode
  243. Input array.
  244. x2 : array_like of str or unicode
  245. Input array.
  246. Returns
  247. -------
  248. add : ndarray
  249. Output array of `bytes_` or `str_`, depending on input types
  250. of the same shape as `x1` and `x2`.
  251. """
  252. arr1 = numpy.asarray(x1)
  253. arr2 = numpy.asarray(x2)
  254. out_size = _get_num_chars(arr1) + _get_num_chars(arr2)
  255. if type(arr1.dtype) != type(arr2.dtype):
  256. # Enforce this for now. The solution to it will be implement add
  257. # as a ufunc. It never worked right on Python 3: bytes + unicode gave
  258. # nonsense unicode + bytes errored, and unicode + object used the
  259. # object dtype itemsize as num chars (worked on short strings).
  260. # bytes + void worked but promoting void->bytes is dubious also.
  261. raise TypeError(
  262. "np.char.add() requires both arrays of the same dtype kind, but "
  263. f"got dtypes: '{arr1.dtype}' and '{arr2.dtype}' (the few cases "
  264. "where this used to work often lead to incorrect results).")
  265. return _vec_string(arr1, type(arr1.dtype)(out_size), '__add__', (arr2,))
  266. def _multiply_dispatcher(a, i):
  267. return (a,)
  268. @array_function_dispatch(_multiply_dispatcher)
  269. def multiply(a, i):
  270. """
  271. Return (a * i), that is string multiple concatenation,
  272. element-wise.
  273. Values in `i` of less than 0 are treated as 0 (which yields an
  274. empty string).
  275. Parameters
  276. ----------
  277. a : array_like of str or unicode
  278. i : array_like of ints
  279. Returns
  280. -------
  281. out : ndarray
  282. Output array of str or unicode, depending on input types
  283. Examples
  284. --------
  285. >>> a = np.array(["a", "b", "c"])
  286. >>> np.char.multiply(x, 3)
  287. array(['aaa', 'bbb', 'ccc'], dtype='<U3')
  288. >>> i = np.array([1, 2, 3])
  289. >>> np.char.multiply(a, i)
  290. array(['a', 'bb', 'ccc'], dtype='<U3')
  291. >>> np.char.multiply(np.array(['a']), i)
  292. array(['a', 'aa', 'aaa'], dtype='<U3')
  293. >>> a = np.array(['a', 'b', 'c', 'd', 'e', 'f']).reshape((2, 3))
  294. >>> np.char.multiply(a, 3)
  295. array([['aaa', 'bbb', 'ccc'],
  296. ['ddd', 'eee', 'fff']], dtype='<U3')
  297. >>> np.char.multiply(a, i)
  298. array([['a', 'bb', 'ccc'],
  299. ['d', 'ee', 'fff']], dtype='<U3')
  300. """
  301. a_arr = numpy.asarray(a)
  302. i_arr = numpy.asarray(i)
  303. if not issubclass(i_arr.dtype.type, integer):
  304. raise ValueError("Can only multiply by integers")
  305. out_size = _get_num_chars(a_arr) * max(int(i_arr.max()), 0)
  306. return _vec_string(
  307. a_arr, type(a_arr.dtype)(out_size), '__mul__', (i_arr,))
  308. def _mod_dispatcher(a, values):
  309. return (a, values)
  310. @array_function_dispatch(_mod_dispatcher)
  311. def mod(a, values):
  312. """
  313. Return (a % i), that is pre-Python 2.6 string formatting
  314. (interpolation), element-wise for a pair of array_likes of str
  315. or unicode.
  316. Parameters
  317. ----------
  318. a : array_like of str or unicode
  319. values : array_like of values
  320. These values will be element-wise interpolated into the string.
  321. Returns
  322. -------
  323. out : ndarray
  324. Output array of str or unicode, depending on input types
  325. See Also
  326. --------
  327. str.__mod__
  328. """
  329. return _to_bytes_or_str_array(
  330. _vec_string(a, object_, '__mod__', (values,)), a)
  331. @array_function_dispatch(_unary_op_dispatcher)
  332. def capitalize(a):
  333. """
  334. Return a copy of `a` with only the first character of each element
  335. capitalized.
  336. Calls `str.capitalize` element-wise.
  337. For 8-bit strings, this method is locale-dependent.
  338. Parameters
  339. ----------
  340. a : array_like of str or unicode
  341. Input array of strings to capitalize.
  342. Returns
  343. -------
  344. out : ndarray
  345. Output array of str or unicode, depending on input
  346. types
  347. See Also
  348. --------
  349. str.capitalize
  350. Examples
  351. --------
  352. >>> c = np.array(['a1b2','1b2a','b2a1','2a1b'],'S4'); c
  353. array(['a1b2', '1b2a', 'b2a1', '2a1b'],
  354. dtype='|S4')
  355. >>> np.char.capitalize(c)
  356. array(['A1b2', '1b2a', 'B2a1', '2a1b'],
  357. dtype='|S4')
  358. """
  359. a_arr = numpy.asarray(a)
  360. return _vec_string(a_arr, a_arr.dtype, 'capitalize')
  361. def _center_dispatcher(a, width, fillchar=None):
  362. return (a,)
  363. @array_function_dispatch(_center_dispatcher)
  364. def center(a, width, fillchar=' '):
  365. """
  366. Return a copy of `a` with its elements centered in a string of
  367. length `width`.
  368. Calls `str.center` element-wise.
  369. Parameters
  370. ----------
  371. a : array_like of str or unicode
  372. width : int
  373. The length of the resulting strings
  374. fillchar : str or unicode, optional
  375. The padding character to use (default is space).
  376. Returns
  377. -------
  378. out : ndarray
  379. Output array of str or unicode, depending on input
  380. types
  381. See Also
  382. --------
  383. str.center
  384. Notes
  385. -----
  386. This function is intended to work with arrays of strings. The
  387. fill character is not applied to numeric types.
  388. Examples
  389. --------
  390. >>> c = np.array(['a1b2','1b2a','b2a1','2a1b']); c
  391. array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='<U4')
  392. >>> np.char.center(c, width=9)
  393. array([' a1b2 ', ' 1b2a ', ' b2a1 ', ' 2a1b '], dtype='<U9')
  394. >>> np.char.center(c, width=9, fillchar='*')
  395. array(['***a1b2**', '***1b2a**', '***b2a1**', '***2a1b**'], dtype='<U9')
  396. >>> np.char.center(c, width=1)
  397. array(['a', '1', 'b', '2'], dtype='<U1')
  398. """
  399. a_arr = numpy.asarray(a)
  400. width_arr = numpy.asarray(width)
  401. size = int(numpy.max(width_arr.flat))
  402. if numpy.issubdtype(a_arr.dtype, numpy.bytes_):
  403. fillchar = asbytes(fillchar)
  404. return _vec_string(
  405. a_arr, type(a_arr.dtype)(size), 'center', (width_arr, fillchar))
  406. def _count_dispatcher(a, sub, start=None, end=None):
  407. return (a,)
  408. @array_function_dispatch(_count_dispatcher)
  409. def count(a, sub, start=0, end=None):
  410. """
  411. Returns an array with the number of non-overlapping occurrences of
  412. substring `sub` in the range [`start`, `end`].
  413. Calls `str.count` element-wise.
  414. Parameters
  415. ----------
  416. a : array_like of str or unicode
  417. sub : str or unicode
  418. The substring to search for.
  419. start, end : int, optional
  420. Optional arguments `start` and `end` are interpreted as slice
  421. notation to specify the range in which to count.
  422. Returns
  423. -------
  424. out : ndarray
  425. Output array of ints.
  426. See Also
  427. --------
  428. str.count
  429. Examples
  430. --------
  431. >>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
  432. >>> c
  433. array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
  434. >>> np.char.count(c, 'A')
  435. array([3, 1, 1])
  436. >>> np.char.count(c, 'aA')
  437. array([3, 1, 0])
  438. >>> np.char.count(c, 'A', start=1, end=4)
  439. array([2, 1, 1])
  440. >>> np.char.count(c, 'A', start=1, end=3)
  441. array([1, 0, 0])
  442. """
  443. return _vec_string(a, int_, 'count', [sub, start] + _clean_args(end))
  444. def _code_dispatcher(a, encoding=None, errors=None):
  445. return (a,)
  446. @array_function_dispatch(_code_dispatcher)
  447. def decode(a, encoding=None, errors=None):
  448. r"""
  449. Calls ``bytes.decode`` element-wise.
  450. The set of available codecs comes from the Python standard library,
  451. and may be extended at runtime. For more information, see the
  452. :mod:`codecs` module.
  453. Parameters
  454. ----------
  455. a : array_like of str or unicode
  456. encoding : str, optional
  457. The name of an encoding
  458. errors : str, optional
  459. Specifies how to handle encoding errors
  460. Returns
  461. -------
  462. out : ndarray
  463. See Also
  464. --------
  465. :py:meth:`bytes.decode`
  466. Notes
  467. -----
  468. The type of the result will depend on the encoding specified.
  469. Examples
  470. --------
  471. >>> c = np.array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@',
  472. ... b'\x81\x82\xc2\xc1\xc2\x82\x81'])
  473. >>> c
  474. array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@',
  475. ... b'\x81\x82\xc2\xc1\xc2\x82\x81'], dtype='|S7')
  476. >>> np.char.decode(c, encoding='cp037')
  477. array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
  478. """
  479. return _to_bytes_or_str_array(
  480. _vec_string(a, object_, 'decode', _clean_args(encoding, errors)))
  481. @array_function_dispatch(_code_dispatcher)
  482. def encode(a, encoding=None, errors=None):
  483. """
  484. Calls `str.encode` element-wise.
  485. The set of available codecs comes from the Python standard library,
  486. and may be extended at runtime. For more information, see the codecs
  487. module.
  488. Parameters
  489. ----------
  490. a : array_like of str or unicode
  491. encoding : str, optional
  492. The name of an encoding
  493. errors : str, optional
  494. Specifies how to handle encoding errors
  495. Returns
  496. -------
  497. out : ndarray
  498. See Also
  499. --------
  500. str.encode
  501. Notes
  502. -----
  503. The type of the result will depend on the encoding specified.
  504. """
  505. return _to_bytes_or_str_array(
  506. _vec_string(a, object_, 'encode', _clean_args(encoding, errors)))
  507. def _endswith_dispatcher(a, suffix, start=None, end=None):
  508. return (a,)
  509. @array_function_dispatch(_endswith_dispatcher)
  510. def endswith(a, suffix, start=0, end=None):
  511. """
  512. Returns a boolean array which is `True` where the string element
  513. in `a` ends with `suffix`, otherwise `False`.
  514. Calls `str.endswith` element-wise.
  515. Parameters
  516. ----------
  517. a : array_like of str or unicode
  518. suffix : str
  519. start, end : int, optional
  520. With optional `start`, test beginning at that position. With
  521. optional `end`, stop comparing at that position.
  522. Returns
  523. -------
  524. out : ndarray
  525. Outputs an array of bools.
  526. See Also
  527. --------
  528. str.endswith
  529. Examples
  530. --------
  531. >>> s = np.array(['foo', 'bar'])
  532. >>> s[0] = 'foo'
  533. >>> s[1] = 'bar'
  534. >>> s
  535. array(['foo', 'bar'], dtype='<U3')
  536. >>> np.char.endswith(s, 'ar')
  537. array([False, True])
  538. >>> np.char.endswith(s, 'a', start=1, end=2)
  539. array([False, True])
  540. """
  541. return _vec_string(
  542. a, bool_, 'endswith', [suffix, start] + _clean_args(end))
  543. def _expandtabs_dispatcher(a, tabsize=None):
  544. return (a,)
  545. @array_function_dispatch(_expandtabs_dispatcher)
  546. def expandtabs(a, tabsize=8):
  547. """
  548. Return a copy of each string element where all tab characters are
  549. replaced by one or more spaces.
  550. Calls `str.expandtabs` element-wise.
  551. Return a copy of each string element where all tab characters are
  552. replaced by one or more spaces, depending on the current column
  553. and the given `tabsize`. The column number is reset to zero after
  554. each newline occurring in the string. This doesn't understand other
  555. non-printing characters or escape sequences.
  556. Parameters
  557. ----------
  558. a : array_like of str or unicode
  559. Input array
  560. tabsize : int, optional
  561. Replace tabs with `tabsize` number of spaces. If not given defaults
  562. to 8 spaces.
  563. Returns
  564. -------
  565. out : ndarray
  566. Output array of str or unicode, depending on input type
  567. See Also
  568. --------
  569. str.expandtabs
  570. """
  571. return _to_bytes_or_str_array(
  572. _vec_string(a, object_, 'expandtabs', (tabsize,)), a)
  573. @array_function_dispatch(_count_dispatcher)
  574. def find(a, sub, start=0, end=None):
  575. """
  576. For each element, return the lowest index in the string where
  577. substring `sub` is found.
  578. Calls `str.find` element-wise.
  579. For each element, return the lowest index in the string where
  580. substring `sub` is found, such that `sub` is contained in the
  581. range [`start`, `end`].
  582. Parameters
  583. ----------
  584. a : array_like of str or unicode
  585. sub : str or unicode
  586. start, end : int, optional
  587. Optional arguments `start` and `end` are interpreted as in
  588. slice notation.
  589. Returns
  590. -------
  591. out : ndarray or int
  592. Output array of ints. Returns -1 if `sub` is not found.
  593. See Also
  594. --------
  595. str.find
  596. Examples
  597. --------
  598. >>> a = np.array(["NumPy is a Python library"])
  599. >>> np.char.find(a, "Python", start=0, end=None)
  600. array([11])
  601. """
  602. return _vec_string(
  603. a, int_, 'find', [sub, start] + _clean_args(end))
  604. @array_function_dispatch(_count_dispatcher)
  605. def index(a, sub, start=0, end=None):
  606. """
  607. Like `find`, but raises `ValueError` when the substring is not found.
  608. Calls `str.index` element-wise.
  609. Parameters
  610. ----------
  611. a : array_like of str or unicode
  612. sub : str or unicode
  613. start, end : int, optional
  614. Returns
  615. -------
  616. out : ndarray
  617. Output array of ints. Returns -1 if `sub` is not found.
  618. See Also
  619. --------
  620. find, str.find
  621. Examples
  622. --------
  623. >>> a = np.array(["Computer Science"])
  624. >>> np.char.index(a, "Science", start=0, end=None)
  625. array([9])
  626. """
  627. return _vec_string(
  628. a, int_, 'index', [sub, start] + _clean_args(end))
  629. @array_function_dispatch(_unary_op_dispatcher)
  630. def isalnum(a):
  631. """
  632. Returns true for each element if all characters in the string are
  633. alphanumeric and there is at least one character, false otherwise.
  634. Calls `str.isalnum` element-wise.
  635. For 8-bit strings, this method is locale-dependent.
  636. Parameters
  637. ----------
  638. a : array_like of str or unicode
  639. Returns
  640. -------
  641. out : ndarray
  642. Output array of str or unicode, depending on input type
  643. See Also
  644. --------
  645. str.isalnum
  646. """
  647. return _vec_string(a, bool_, 'isalnum')
  648. @array_function_dispatch(_unary_op_dispatcher)
  649. def isalpha(a):
  650. """
  651. Returns true for each element if all characters in the string are
  652. alphabetic and there is at least one character, false otherwise.
  653. Calls `str.isalpha` element-wise.
  654. For 8-bit strings, this method is locale-dependent.
  655. Parameters
  656. ----------
  657. a : array_like of str or unicode
  658. Returns
  659. -------
  660. out : ndarray
  661. Output array of bools
  662. See Also
  663. --------
  664. str.isalpha
  665. """
  666. return _vec_string(a, bool_, 'isalpha')
  667. @array_function_dispatch(_unary_op_dispatcher)
  668. def isdigit(a):
  669. """
  670. Returns true for each element if all characters in the string are
  671. digits and there is at least one character, false otherwise.
  672. Calls `str.isdigit` element-wise.
  673. For 8-bit strings, this method is locale-dependent.
  674. Parameters
  675. ----------
  676. a : array_like of str or unicode
  677. Returns
  678. -------
  679. out : ndarray
  680. Output array of bools
  681. See Also
  682. --------
  683. str.isdigit
  684. Examples
  685. --------
  686. >>> a = np.array(['a', 'b', '0'])
  687. >>> np.char.isdigit(a)
  688. array([False, False, True])
  689. >>> a = np.array([['a', 'b', '0'], ['c', '1', '2']])
  690. >>> np.char.isdigit(a)
  691. array([[False, False, True], [False, True, True]])
  692. """
  693. return _vec_string(a, bool_, 'isdigit')
  694. @array_function_dispatch(_unary_op_dispatcher)
  695. def islower(a):
  696. """
  697. Returns true for each element if all cased characters in the
  698. string are lowercase and there is at least one cased character,
  699. false otherwise.
  700. Calls `str.islower` element-wise.
  701. For 8-bit strings, this method is locale-dependent.
  702. Parameters
  703. ----------
  704. a : array_like of str or unicode
  705. Returns
  706. -------
  707. out : ndarray
  708. Output array of bools
  709. See Also
  710. --------
  711. str.islower
  712. """
  713. return _vec_string(a, bool_, 'islower')
  714. @array_function_dispatch(_unary_op_dispatcher)
  715. def isspace(a):
  716. """
  717. Returns true for each element if there are only whitespace
  718. characters in the string and there is at least one character,
  719. false otherwise.
  720. Calls `str.isspace` element-wise.
  721. For 8-bit strings, this method is locale-dependent.
  722. Parameters
  723. ----------
  724. a : array_like of str or unicode
  725. Returns
  726. -------
  727. out : ndarray
  728. Output array of bools
  729. See Also
  730. --------
  731. str.isspace
  732. """
  733. return _vec_string(a, bool_, 'isspace')
  734. @array_function_dispatch(_unary_op_dispatcher)
  735. def istitle(a):
  736. """
  737. Returns true for each element if the element is a titlecased
  738. string and there is at least one character, false otherwise.
  739. Call `str.istitle` element-wise.
  740. For 8-bit strings, this method is locale-dependent.
  741. Parameters
  742. ----------
  743. a : array_like of str or unicode
  744. Returns
  745. -------
  746. out : ndarray
  747. Output array of bools
  748. See Also
  749. --------
  750. str.istitle
  751. """
  752. return _vec_string(a, bool_, 'istitle')
  753. @array_function_dispatch(_unary_op_dispatcher)
  754. def isupper(a):
  755. """
  756. Return true for each element if all cased characters in the
  757. string are uppercase and there is at least one character, false
  758. otherwise.
  759. Call `str.isupper` element-wise.
  760. For 8-bit strings, this method is locale-dependent.
  761. Parameters
  762. ----------
  763. a : array_like of str or unicode
  764. Returns
  765. -------
  766. out : ndarray
  767. Output array of bools
  768. See Also
  769. --------
  770. str.isupper
  771. Examples
  772. --------
  773. >>> str = "GHC"
  774. >>> np.char.isupper(str)
  775. array(True)
  776. >>> a = np.array(["hello", "HELLO", "Hello"])
  777. >>> np.char.isupper(a)
  778. array([False, True, False])
  779. """
  780. return _vec_string(a, bool_, 'isupper')
  781. def _join_dispatcher(sep, seq):
  782. return (sep, seq)
  783. @array_function_dispatch(_join_dispatcher)
  784. def join(sep, seq):
  785. """
  786. Return a string which is the concatenation of the strings in the
  787. sequence `seq`.
  788. Calls `str.join` element-wise.
  789. Parameters
  790. ----------
  791. sep : array_like of str or unicode
  792. seq : array_like of str or unicode
  793. Returns
  794. -------
  795. out : ndarray
  796. Output array of str or unicode, depending on input types
  797. See Also
  798. --------
  799. str.join
  800. Examples
  801. --------
  802. >>> np.char.join('-', 'osd')
  803. array('o-s-d', dtype='<U5')
  804. >>> np.char.join(['-', '.'], ['ghc', 'osd'])
  805. array(['g-h-c', 'o.s.d'], dtype='<U5')
  806. """
  807. return _to_bytes_or_str_array(
  808. _vec_string(sep, object_, 'join', (seq,)), seq)
  809. def _just_dispatcher(a, width, fillchar=None):
  810. return (a,)
  811. @array_function_dispatch(_just_dispatcher)
  812. def ljust(a, width, fillchar=' '):
  813. """
  814. Return an array with the elements of `a` left-justified in a
  815. string of length `width`.
  816. Calls `str.ljust` element-wise.
  817. Parameters
  818. ----------
  819. a : array_like of str or unicode
  820. width : int
  821. The length of the resulting strings
  822. fillchar : str or unicode, optional
  823. The character to use for padding
  824. Returns
  825. -------
  826. out : ndarray
  827. Output array of str or unicode, depending on input type
  828. See Also
  829. --------
  830. str.ljust
  831. """
  832. a_arr = numpy.asarray(a)
  833. width_arr = numpy.asarray(width)
  834. size = int(numpy.max(width_arr.flat))
  835. if numpy.issubdtype(a_arr.dtype, numpy.bytes_):
  836. fillchar = asbytes(fillchar)
  837. return _vec_string(
  838. a_arr, type(a_arr.dtype)(size), 'ljust', (width_arr, fillchar))
  839. @array_function_dispatch(_unary_op_dispatcher)
  840. def lower(a):
  841. """
  842. Return an array with the elements converted to lowercase.
  843. Call `str.lower` element-wise.
  844. For 8-bit strings, this method is locale-dependent.
  845. Parameters
  846. ----------
  847. a : array_like, {str, unicode}
  848. Input array.
  849. Returns
  850. -------
  851. out : ndarray, {str, unicode}
  852. Output array of str or unicode, depending on input type
  853. See Also
  854. --------
  855. str.lower
  856. Examples
  857. --------
  858. >>> c = np.array(['A1B C', '1BCA', 'BCA1']); c
  859. array(['A1B C', '1BCA', 'BCA1'], dtype='<U5')
  860. >>> np.char.lower(c)
  861. array(['a1b c', '1bca', 'bca1'], dtype='<U5')
  862. """
  863. a_arr = numpy.asarray(a)
  864. return _vec_string(a_arr, a_arr.dtype, 'lower')
  865. def _strip_dispatcher(a, chars=None):
  866. return (a,)
  867. @array_function_dispatch(_strip_dispatcher)
  868. def lstrip(a, chars=None):
  869. """
  870. For each element in `a`, return a copy with the leading characters
  871. removed.
  872. Calls `str.lstrip` element-wise.
  873. Parameters
  874. ----------
  875. a : array-like, {str, unicode}
  876. Input array.
  877. chars : {str, unicode}, optional
  878. The `chars` argument is a string specifying the set of
  879. characters to be removed. If omitted or None, the `chars`
  880. argument defaults to removing whitespace. The `chars` argument
  881. is not a prefix; rather, all combinations of its values are
  882. stripped.
  883. Returns
  884. -------
  885. out : ndarray, {str, unicode}
  886. Output array of str or unicode, depending on input type
  887. See Also
  888. --------
  889. str.lstrip
  890. Examples
  891. --------
  892. >>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
  893. >>> c
  894. array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
  895. The 'a' variable is unstripped from c[1] because whitespace leading.
  896. >>> np.char.lstrip(c, 'a')
  897. array(['AaAaA', ' aA ', 'bBABba'], dtype='<U7')
  898. >>> np.char.lstrip(c, 'A') # leaves c unchanged
  899. array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
  900. >>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, '')).all()
  901. ... # XXX: is this a regression? This used to return True
  902. ... # np.char.lstrip(c,'') does not modify c at all.
  903. False
  904. >>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, None)).all()
  905. True
  906. """
  907. a_arr = numpy.asarray(a)
  908. return _vec_string(a_arr, a_arr.dtype, 'lstrip', (chars,))
  909. def _partition_dispatcher(a, sep):
  910. return (a,)
  911. @array_function_dispatch(_partition_dispatcher)
  912. def partition(a, sep):
  913. """
  914. Partition each element in `a` around `sep`.
  915. Calls `str.partition` element-wise.
  916. For each element in `a`, split the element as the first
  917. occurrence of `sep`, and return 3 strings containing the part
  918. before the separator, the separator itself, and the part after
  919. the separator. If the separator is not found, return 3 strings
  920. containing the string itself, followed by two empty strings.
  921. Parameters
  922. ----------
  923. a : array_like, {str, unicode}
  924. Input array
  925. sep : {str, unicode}
  926. Separator to split each string element in `a`.
  927. Returns
  928. -------
  929. out : ndarray, {str, unicode}
  930. Output array of str or unicode, depending on input type.
  931. The output array will have an extra dimension with 3
  932. elements per input element.
  933. See Also
  934. --------
  935. str.partition
  936. """
  937. return _to_bytes_or_str_array(
  938. _vec_string(a, object_, 'partition', (sep,)), a)
  939. def _replace_dispatcher(a, old, new, count=None):
  940. return (a,)
  941. @array_function_dispatch(_replace_dispatcher)
  942. def replace(a, old, new, count=None):
  943. """
  944. For each element in `a`, return a copy of the string with all
  945. occurrences of substring `old` replaced by `new`.
  946. Calls `str.replace` element-wise.
  947. Parameters
  948. ----------
  949. a : array-like of str or unicode
  950. old, new : str or unicode
  951. count : int, optional
  952. If the optional argument `count` is given, only the first
  953. `count` occurrences are replaced.
  954. Returns
  955. -------
  956. out : ndarray
  957. Output array of str or unicode, depending on input type
  958. See Also
  959. --------
  960. str.replace
  961. Examples
  962. --------
  963. >>> a = np.array(["That is a mango", "Monkeys eat mangos"])
  964. >>> np.char.replace(a, 'mango', 'banana')
  965. array(['That is a banana', 'Monkeys eat bananas'], dtype='<U19')
  966. >>> a = np.array(["The dish is fresh", "This is it"])
  967. >>> np.char.replace(a, 'is', 'was')
  968. array(['The dwash was fresh', 'Thwas was it'], dtype='<U19')
  969. """
  970. return _to_bytes_or_str_array(
  971. _vec_string(a, object_, 'replace', [old, new] + _clean_args(count)), a)
  972. @array_function_dispatch(_count_dispatcher)
  973. def rfind(a, sub, start=0, end=None):
  974. """
  975. For each element in `a`, return the highest index in the string
  976. where substring `sub` is found, such that `sub` is contained
  977. within [`start`, `end`].
  978. Calls `str.rfind` element-wise.
  979. Parameters
  980. ----------
  981. a : array-like of str or unicode
  982. sub : str or unicode
  983. start, end : int, optional
  984. Optional arguments `start` and `end` are interpreted as in
  985. slice notation.
  986. Returns
  987. -------
  988. out : ndarray
  989. Output array of ints. Return -1 on failure.
  990. See Also
  991. --------
  992. str.rfind
  993. """
  994. return _vec_string(
  995. a, int_, 'rfind', [sub, start] + _clean_args(end))
  996. @array_function_dispatch(_count_dispatcher)
  997. def rindex(a, sub, start=0, end=None):
  998. """
  999. Like `rfind`, but raises `ValueError` when the substring `sub` is
  1000. not found.
  1001. Calls `str.rindex` element-wise.
  1002. Parameters
  1003. ----------
  1004. a : array-like of str or unicode
  1005. sub : str or unicode
  1006. start, end : int, optional
  1007. Returns
  1008. -------
  1009. out : ndarray
  1010. Output array of ints.
  1011. See Also
  1012. --------
  1013. rfind, str.rindex
  1014. """
  1015. return _vec_string(
  1016. a, int_, 'rindex', [sub, start] + _clean_args(end))
  1017. @array_function_dispatch(_just_dispatcher)
  1018. def rjust(a, width, fillchar=' '):
  1019. """
  1020. Return an array with the elements of `a` right-justified in a
  1021. string of length `width`.
  1022. Calls `str.rjust` element-wise.
  1023. Parameters
  1024. ----------
  1025. a : array_like of str or unicode
  1026. width : int
  1027. The length of the resulting strings
  1028. fillchar : str or unicode, optional
  1029. The character to use for padding
  1030. Returns
  1031. -------
  1032. out : ndarray
  1033. Output array of str or unicode, depending on input type
  1034. See Also
  1035. --------
  1036. str.rjust
  1037. """
  1038. a_arr = numpy.asarray(a)
  1039. width_arr = numpy.asarray(width)
  1040. size = int(numpy.max(width_arr.flat))
  1041. if numpy.issubdtype(a_arr.dtype, numpy.bytes_):
  1042. fillchar = asbytes(fillchar)
  1043. return _vec_string(
  1044. a_arr, type(a_arr.dtype)(size), 'rjust', (width_arr, fillchar))
  1045. @array_function_dispatch(_partition_dispatcher)
  1046. def rpartition(a, sep):
  1047. """
  1048. Partition (split) each element around the right-most separator.
  1049. Calls `str.rpartition` element-wise.
  1050. For each element in `a`, split the element as the last
  1051. occurrence of `sep`, and return 3 strings containing the part
  1052. before the separator, the separator itself, and the part after
  1053. the separator. If the separator is not found, return 3 strings
  1054. containing the string itself, followed by two empty strings.
  1055. Parameters
  1056. ----------
  1057. a : array_like of str or unicode
  1058. Input array
  1059. sep : str or unicode
  1060. Right-most separator to split each element in array.
  1061. Returns
  1062. -------
  1063. out : ndarray
  1064. Output array of string or unicode, depending on input
  1065. type. The output array will have an extra dimension with
  1066. 3 elements per input element.
  1067. See Also
  1068. --------
  1069. str.rpartition
  1070. """
  1071. return _to_bytes_or_str_array(
  1072. _vec_string(a, object_, 'rpartition', (sep,)), a)
  1073. def _split_dispatcher(a, sep=None, maxsplit=None):
  1074. return (a,)
  1075. @array_function_dispatch(_split_dispatcher)
  1076. def rsplit(a, sep=None, maxsplit=None):
  1077. """
  1078. For each element in `a`, return a list of the words in the
  1079. string, using `sep` as the delimiter string.
  1080. Calls `str.rsplit` element-wise.
  1081. Except for splitting from the right, `rsplit`
  1082. behaves like `split`.
  1083. Parameters
  1084. ----------
  1085. a : array_like of str or unicode
  1086. sep : str or unicode, optional
  1087. If `sep` is not specified or None, any whitespace string
  1088. is a separator.
  1089. maxsplit : int, optional
  1090. If `maxsplit` is given, at most `maxsplit` splits are done,
  1091. the rightmost ones.
  1092. Returns
  1093. -------
  1094. out : ndarray
  1095. Array of list objects
  1096. See Also
  1097. --------
  1098. str.rsplit, split
  1099. """
  1100. # This will return an array of lists of different sizes, so we
  1101. # leave it as an object array
  1102. return _vec_string(
  1103. a, object_, 'rsplit', [sep] + _clean_args(maxsplit))
  1104. def _strip_dispatcher(a, chars=None):
  1105. return (a,)
  1106. @array_function_dispatch(_strip_dispatcher)
  1107. def rstrip(a, chars=None):
  1108. """
  1109. For each element in `a`, return a copy with the trailing
  1110. characters removed.
  1111. Calls `str.rstrip` element-wise.
  1112. Parameters
  1113. ----------
  1114. a : array-like of str or unicode
  1115. chars : str or unicode, optional
  1116. The `chars` argument is a string specifying the set of
  1117. characters to be removed. If omitted or None, the `chars`
  1118. argument defaults to removing whitespace. The `chars` argument
  1119. is not a suffix; rather, all combinations of its values are
  1120. stripped.
  1121. Returns
  1122. -------
  1123. out : ndarray
  1124. Output array of str or unicode, depending on input type
  1125. See Also
  1126. --------
  1127. str.rstrip
  1128. Examples
  1129. --------
  1130. >>> c = np.array(['aAaAaA', 'abBABba'], dtype='S7'); c
  1131. array(['aAaAaA', 'abBABba'],
  1132. dtype='|S7')
  1133. >>> np.char.rstrip(c, b'a')
  1134. array(['aAaAaA', 'abBABb'],
  1135. dtype='|S7')
  1136. >>> np.char.rstrip(c, b'A')
  1137. array(['aAaAa', 'abBABba'],
  1138. dtype='|S7')
  1139. """
  1140. a_arr = numpy.asarray(a)
  1141. return _vec_string(a_arr, a_arr.dtype, 'rstrip', (chars,))
  1142. @array_function_dispatch(_split_dispatcher)
  1143. def split(a, sep=None, maxsplit=None):
  1144. """
  1145. For each element in `a`, return a list of the words in the
  1146. string, using `sep` as the delimiter string.
  1147. Calls `str.split` element-wise.
  1148. Parameters
  1149. ----------
  1150. a : array_like of str or unicode
  1151. sep : str or unicode, optional
  1152. If `sep` is not specified or None, any whitespace string is a
  1153. separator.
  1154. maxsplit : int, optional
  1155. If `maxsplit` is given, at most `maxsplit` splits are done.
  1156. Returns
  1157. -------
  1158. out : ndarray
  1159. Array of list objects
  1160. See Also
  1161. --------
  1162. str.split, rsplit
  1163. """
  1164. # This will return an array of lists of different sizes, so we
  1165. # leave it as an object array
  1166. return _vec_string(
  1167. a, object_, 'split', [sep] + _clean_args(maxsplit))
  1168. def _splitlines_dispatcher(a, keepends=None):
  1169. return (a,)
  1170. @array_function_dispatch(_splitlines_dispatcher)
  1171. def splitlines(a, keepends=None):
  1172. """
  1173. For each element in `a`, return a list of the lines in the
  1174. element, breaking at line boundaries.
  1175. Calls `str.splitlines` element-wise.
  1176. Parameters
  1177. ----------
  1178. a : array_like of str or unicode
  1179. keepends : bool, optional
  1180. Line breaks are not included in the resulting list unless
  1181. keepends is given and true.
  1182. Returns
  1183. -------
  1184. out : ndarray
  1185. Array of list objects
  1186. See Also
  1187. --------
  1188. str.splitlines
  1189. """
  1190. return _vec_string(
  1191. a, object_, 'splitlines', _clean_args(keepends))
  1192. def _startswith_dispatcher(a, prefix, start=None, end=None):
  1193. return (a,)
  1194. @array_function_dispatch(_startswith_dispatcher)
  1195. def startswith(a, prefix, start=0, end=None):
  1196. """
  1197. Returns a boolean array which is `True` where the string element
  1198. in `a` starts with `prefix`, otherwise `False`.
  1199. Calls `str.startswith` element-wise.
  1200. Parameters
  1201. ----------
  1202. a : array_like of str or unicode
  1203. prefix : str
  1204. start, end : int, optional
  1205. With optional `start`, test beginning at that position. With
  1206. optional `end`, stop comparing at that position.
  1207. Returns
  1208. -------
  1209. out : ndarray
  1210. Array of booleans
  1211. See Also
  1212. --------
  1213. str.startswith
  1214. """
  1215. return _vec_string(
  1216. a, bool_, 'startswith', [prefix, start] + _clean_args(end))
  1217. @array_function_dispatch(_strip_dispatcher)
  1218. def strip(a, chars=None):
  1219. """
  1220. For each element in `a`, return a copy with the leading and
  1221. trailing characters removed.
  1222. Calls `str.strip` element-wise.
  1223. Parameters
  1224. ----------
  1225. a : array-like of str or unicode
  1226. chars : str or unicode, optional
  1227. The `chars` argument is a string specifying the set of
  1228. characters to be removed. If omitted or None, the `chars`
  1229. argument defaults to removing whitespace. The `chars` argument
  1230. is not a prefix or suffix; rather, all combinations of its
  1231. values are stripped.
  1232. Returns
  1233. -------
  1234. out : ndarray
  1235. Output array of str or unicode, depending on input type
  1236. See Also
  1237. --------
  1238. str.strip
  1239. Examples
  1240. --------
  1241. >>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
  1242. >>> c
  1243. array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
  1244. >>> np.char.strip(c)
  1245. array(['aAaAaA', 'aA', 'abBABba'], dtype='<U7')
  1246. >>> np.char.strip(c, 'a') # 'a' unstripped from c[1] because whitespace leads
  1247. array(['AaAaA', ' aA ', 'bBABb'], dtype='<U7')
  1248. >>> np.char.strip(c, 'A') # 'A' unstripped from c[1] because (unprinted) ws trails
  1249. array(['aAaAa', ' aA ', 'abBABba'], dtype='<U7')
  1250. """
  1251. a_arr = numpy.asarray(a)
  1252. return _vec_string(a_arr, a_arr.dtype, 'strip', _clean_args(chars))
  1253. @array_function_dispatch(_unary_op_dispatcher)
  1254. def swapcase(a):
  1255. """
  1256. Return element-wise a copy of the string with
  1257. uppercase characters converted to lowercase and vice versa.
  1258. Calls `str.swapcase` element-wise.
  1259. For 8-bit strings, this method is locale-dependent.
  1260. Parameters
  1261. ----------
  1262. a : array_like, {str, unicode}
  1263. Input array.
  1264. Returns
  1265. -------
  1266. out : ndarray, {str, unicode}
  1267. Output array of str or unicode, depending on input type
  1268. See Also
  1269. --------
  1270. str.swapcase
  1271. Examples
  1272. --------
  1273. >>> c=np.array(['a1B c','1b Ca','b Ca1','cA1b'],'S5'); c
  1274. array(['a1B c', '1b Ca', 'b Ca1', 'cA1b'],
  1275. dtype='|S5')
  1276. >>> np.char.swapcase(c)
  1277. array(['A1b C', '1B cA', 'B cA1', 'Ca1B'],
  1278. dtype='|S5')
  1279. """
  1280. a_arr = numpy.asarray(a)
  1281. return _vec_string(a_arr, a_arr.dtype, 'swapcase')
  1282. @array_function_dispatch(_unary_op_dispatcher)
  1283. def title(a):
  1284. """
  1285. Return element-wise title cased version of string or unicode.
  1286. Title case words start with uppercase characters, all remaining cased
  1287. characters are lowercase.
  1288. Calls `str.title` element-wise.
  1289. For 8-bit strings, this method is locale-dependent.
  1290. Parameters
  1291. ----------
  1292. a : array_like, {str, unicode}
  1293. Input array.
  1294. Returns
  1295. -------
  1296. out : ndarray
  1297. Output array of str or unicode, depending on input type
  1298. See Also
  1299. --------
  1300. str.title
  1301. Examples
  1302. --------
  1303. >>> c=np.array(['a1b c','1b ca','b ca1','ca1b'],'S5'); c
  1304. array(['a1b c', '1b ca', 'b ca1', 'ca1b'],
  1305. dtype='|S5')
  1306. >>> np.char.title(c)
  1307. array(['A1B C', '1B Ca', 'B Ca1', 'Ca1B'],
  1308. dtype='|S5')
  1309. """
  1310. a_arr = numpy.asarray(a)
  1311. return _vec_string(a_arr, a_arr.dtype, 'title')
  1312. def _translate_dispatcher(a, table, deletechars=None):
  1313. return (a,)
  1314. @array_function_dispatch(_translate_dispatcher)
  1315. def translate(a, table, deletechars=None):
  1316. """
  1317. For each element in `a`, return a copy of the string where all
  1318. characters occurring in the optional argument `deletechars` are
  1319. removed, and the remaining characters have been mapped through the
  1320. given translation table.
  1321. Calls `str.translate` element-wise.
  1322. Parameters
  1323. ----------
  1324. a : array-like of str or unicode
  1325. table : str of length 256
  1326. deletechars : str
  1327. Returns
  1328. -------
  1329. out : ndarray
  1330. Output array of str or unicode, depending on input type
  1331. See Also
  1332. --------
  1333. str.translate
  1334. """
  1335. a_arr = numpy.asarray(a)
  1336. if issubclass(a_arr.dtype.type, str_):
  1337. return _vec_string(
  1338. a_arr, a_arr.dtype, 'translate', (table,))
  1339. else:
  1340. return _vec_string(
  1341. a_arr, a_arr.dtype, 'translate', [table] + _clean_args(deletechars))
  1342. @array_function_dispatch(_unary_op_dispatcher)
  1343. def upper(a):
  1344. """
  1345. Return an array with the elements converted to uppercase.
  1346. Calls `str.upper` element-wise.
  1347. For 8-bit strings, this method is locale-dependent.
  1348. Parameters
  1349. ----------
  1350. a : array_like, {str, unicode}
  1351. Input array.
  1352. Returns
  1353. -------
  1354. out : ndarray, {str, unicode}
  1355. Output array of str or unicode, depending on input type
  1356. See Also
  1357. --------
  1358. str.upper
  1359. Examples
  1360. --------
  1361. >>> c = np.array(['a1b c', '1bca', 'bca1']); c
  1362. array(['a1b c', '1bca', 'bca1'], dtype='<U5')
  1363. >>> np.char.upper(c)
  1364. array(['A1B C', '1BCA', 'BCA1'], dtype='<U5')
  1365. """
  1366. a_arr = numpy.asarray(a)
  1367. return _vec_string(a_arr, a_arr.dtype, 'upper')
  1368. def _zfill_dispatcher(a, width):
  1369. return (a,)
  1370. @array_function_dispatch(_zfill_dispatcher)
  1371. def zfill(a, width):
  1372. """
  1373. Return the numeric string left-filled with zeros
  1374. Calls `str.zfill` element-wise.
  1375. Parameters
  1376. ----------
  1377. a : array_like, {str, unicode}
  1378. Input array.
  1379. width : int
  1380. Width of string to left-fill elements in `a`.
  1381. Returns
  1382. -------
  1383. out : ndarray, {str, unicode}
  1384. Output array of str or unicode, depending on input type
  1385. See Also
  1386. --------
  1387. str.zfill
  1388. """
  1389. a_arr = numpy.asarray(a)
  1390. width_arr = numpy.asarray(width)
  1391. size = int(numpy.max(width_arr.flat))
  1392. return _vec_string(
  1393. a_arr, type(a_arr.dtype)(size), 'zfill', (width_arr,))
  1394. @array_function_dispatch(_unary_op_dispatcher)
  1395. def isnumeric(a):
  1396. """
  1397. For each element, return True if there are only numeric
  1398. characters in the element.
  1399. Calls `str.isnumeric` element-wise.
  1400. Numeric characters include digit characters, and all characters
  1401. that have the Unicode numeric value property, e.g. ``U+2155,
  1402. VULGAR FRACTION ONE FIFTH``.
  1403. Parameters
  1404. ----------
  1405. a : array_like, unicode
  1406. Input array.
  1407. Returns
  1408. -------
  1409. out : ndarray, bool
  1410. Array of booleans of same shape as `a`.
  1411. See Also
  1412. --------
  1413. str.isnumeric
  1414. Examples
  1415. --------
  1416. >>> np.char.isnumeric(['123', '123abc', '9.0', '1/4', 'VIII'])
  1417. array([ True, False, False, False, False])
  1418. """
  1419. if not _is_unicode(a):
  1420. raise TypeError("isnumeric is only available for Unicode strings and arrays")
  1421. return _vec_string(a, bool_, 'isnumeric')
  1422. @array_function_dispatch(_unary_op_dispatcher)
  1423. def isdecimal(a):
  1424. """
  1425. For each element, return True if there are only decimal
  1426. characters in the element.
  1427. Calls `str.isdecimal` element-wise.
  1428. Decimal characters include digit characters, and all characters
  1429. that can be used to form decimal-radix numbers,
  1430. e.g. ``U+0660, ARABIC-INDIC DIGIT ZERO``.
  1431. Parameters
  1432. ----------
  1433. a : array_like, unicode
  1434. Input array.
  1435. Returns
  1436. -------
  1437. out : ndarray, bool
  1438. Array of booleans identical in shape to `a`.
  1439. See Also
  1440. --------
  1441. str.isdecimal
  1442. Examples
  1443. --------
  1444. >>> np.char.isdecimal(['12345', '4.99', '123ABC', ''])
  1445. array([ True, False, False, False])
  1446. """
  1447. if not _is_unicode(a):
  1448. raise TypeError(
  1449. "isdecimal is only available for Unicode strings and arrays")
  1450. return _vec_string(a, bool_, 'isdecimal')
  1451. @set_module('numpy')
  1452. class chararray(ndarray):
  1453. """
  1454. chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0,
  1455. strides=None, order=None)
  1456. Provides a convenient view on arrays of string and unicode values.
  1457. .. note::
  1458. The `chararray` class exists for backwards compatibility with
  1459. Numarray, it is not recommended for new development. Starting from numpy
  1460. 1.4, if one needs arrays of strings, it is recommended to use arrays of
  1461. `dtype` `object_`, `bytes_` or `str_`, and use the free functions
  1462. in the `numpy.char` module for fast vectorized string operations.
  1463. Versus a regular NumPy array of type `str` or `unicode`, this
  1464. class adds the following functionality:
  1465. 1) values automatically have whitespace removed from the end
  1466. when indexed
  1467. 2) comparison operators automatically remove whitespace from the
  1468. end when comparing values
  1469. 3) vectorized string operations are provided as methods
  1470. (e.g. `.endswith`) and infix operators (e.g. ``"+", "*", "%"``)
  1471. chararrays should be created using `numpy.char.array` or
  1472. `numpy.char.asarray`, rather than this constructor directly.
  1473. This constructor creates the array, using `buffer` (with `offset`
  1474. and `strides`) if it is not ``None``. If `buffer` is ``None``, then
  1475. constructs a new array with `strides` in "C order", unless both
  1476. ``len(shape) >= 2`` and ``order='F'``, in which case `strides`
  1477. is in "Fortran order".
  1478. Methods
  1479. -------
  1480. astype
  1481. argsort
  1482. copy
  1483. count
  1484. decode
  1485. dump
  1486. dumps
  1487. encode
  1488. endswith
  1489. expandtabs
  1490. fill
  1491. find
  1492. flatten
  1493. getfield
  1494. index
  1495. isalnum
  1496. isalpha
  1497. isdecimal
  1498. isdigit
  1499. islower
  1500. isnumeric
  1501. isspace
  1502. istitle
  1503. isupper
  1504. item
  1505. join
  1506. ljust
  1507. lower
  1508. lstrip
  1509. nonzero
  1510. put
  1511. ravel
  1512. repeat
  1513. replace
  1514. reshape
  1515. resize
  1516. rfind
  1517. rindex
  1518. rjust
  1519. rsplit
  1520. rstrip
  1521. searchsorted
  1522. setfield
  1523. setflags
  1524. sort
  1525. split
  1526. splitlines
  1527. squeeze
  1528. startswith
  1529. strip
  1530. swapaxes
  1531. swapcase
  1532. take
  1533. title
  1534. tofile
  1535. tolist
  1536. tostring
  1537. translate
  1538. transpose
  1539. upper
  1540. view
  1541. zfill
  1542. Parameters
  1543. ----------
  1544. shape : tuple
  1545. Shape of the array.
  1546. itemsize : int, optional
  1547. Length of each array element, in number of characters. Default is 1.
  1548. unicode : bool, optional
  1549. Are the array elements of type unicode (True) or string (False).
  1550. Default is False.
  1551. buffer : object exposing the buffer interface or str, optional
  1552. Memory address of the start of the array data. Default is None,
  1553. in which case a new array is created.
  1554. offset : int, optional
  1555. Fixed stride displacement from the beginning of an axis?
  1556. Default is 0. Needs to be >=0.
  1557. strides : array_like of ints, optional
  1558. Strides for the array (see `ndarray.strides` for full description).
  1559. Default is None.
  1560. order : {'C', 'F'}, optional
  1561. The order in which the array data is stored in memory: 'C' ->
  1562. "row major" order (the default), 'F' -> "column major"
  1563. (Fortran) order.
  1564. Examples
  1565. --------
  1566. >>> charar = np.chararray((3, 3))
  1567. >>> charar[:] = 'a'
  1568. >>> charar
  1569. chararray([[b'a', b'a', b'a'],
  1570. [b'a', b'a', b'a'],
  1571. [b'a', b'a', b'a']], dtype='|S1')
  1572. >>> charar = np.chararray(charar.shape, itemsize=5)
  1573. >>> charar[:] = 'abc'
  1574. >>> charar
  1575. chararray([[b'abc', b'abc', b'abc'],
  1576. [b'abc', b'abc', b'abc'],
  1577. [b'abc', b'abc', b'abc']], dtype='|S5')
  1578. """
  1579. def __new__(subtype, shape, itemsize=1, unicode=False, buffer=None,
  1580. offset=0, strides=None, order='C'):
  1581. global _globalvar
  1582. if unicode:
  1583. dtype = str_
  1584. else:
  1585. dtype = bytes_
  1586. # force itemsize to be a Python int, since using NumPy integer
  1587. # types results in itemsize.itemsize being used as the size of
  1588. # strings in the new array.
  1589. itemsize = int(itemsize)
  1590. if isinstance(buffer, str):
  1591. # unicode objects do not have the buffer interface
  1592. filler = buffer
  1593. buffer = None
  1594. else:
  1595. filler = None
  1596. _globalvar = 1
  1597. if buffer is None:
  1598. self = ndarray.__new__(subtype, shape, (dtype, itemsize),
  1599. order=order)
  1600. else:
  1601. self = ndarray.__new__(subtype, shape, (dtype, itemsize),
  1602. buffer=buffer,
  1603. offset=offset, strides=strides,
  1604. order=order)
  1605. if filler is not None:
  1606. self[...] = filler
  1607. _globalvar = 0
  1608. return self
  1609. def __array_finalize__(self, obj):
  1610. # The b is a special case because it is used for reconstructing.
  1611. if not _globalvar and self.dtype.char not in 'SUbc':
  1612. raise ValueError("Can only create a chararray from string data.")
  1613. def __getitem__(self, obj):
  1614. val = ndarray.__getitem__(self, obj)
  1615. if isinstance(val, character):
  1616. temp = val.rstrip()
  1617. if len(temp) == 0:
  1618. val = ''
  1619. else:
  1620. val = temp
  1621. return val
  1622. # IMPLEMENTATION NOTE: Most of the methods of this class are
  1623. # direct delegations to the free functions in this module.
  1624. # However, those that return an array of strings should instead
  1625. # return a chararray, so some extra wrapping is required.
  1626. def __eq__(self, other):
  1627. """
  1628. Return (self == other) element-wise.
  1629. See Also
  1630. --------
  1631. equal
  1632. """
  1633. return equal(self, other)
  1634. def __ne__(self, other):
  1635. """
  1636. Return (self != other) element-wise.
  1637. See Also
  1638. --------
  1639. not_equal
  1640. """
  1641. return not_equal(self, other)
  1642. def __ge__(self, other):
  1643. """
  1644. Return (self >= other) element-wise.
  1645. See Also
  1646. --------
  1647. greater_equal
  1648. """
  1649. return greater_equal(self, other)
  1650. def __le__(self, other):
  1651. """
  1652. Return (self <= other) element-wise.
  1653. See Also
  1654. --------
  1655. less_equal
  1656. """
  1657. return less_equal(self, other)
  1658. def __gt__(self, other):
  1659. """
  1660. Return (self > other) element-wise.
  1661. See Also
  1662. --------
  1663. greater
  1664. """
  1665. return greater(self, other)
  1666. def __lt__(self, other):
  1667. """
  1668. Return (self < other) element-wise.
  1669. See Also
  1670. --------
  1671. less
  1672. """
  1673. return less(self, other)
  1674. def __add__(self, other):
  1675. """
  1676. Return (self + other), that is string concatenation,
  1677. element-wise for a pair of array_likes of str or unicode.
  1678. See Also
  1679. --------
  1680. add
  1681. """
  1682. return asarray(add(self, other))
  1683. def __radd__(self, other):
  1684. """
  1685. Return (other + self), that is string concatenation,
  1686. element-wise for a pair of array_likes of `bytes_` or `str_`.
  1687. See Also
  1688. --------
  1689. add
  1690. """
  1691. return asarray(add(numpy.asarray(other), self))
  1692. def __mul__(self, i):
  1693. """
  1694. Return (self * i), that is string multiple concatenation,
  1695. element-wise.
  1696. See Also
  1697. --------
  1698. multiply
  1699. """
  1700. return asarray(multiply(self, i))
  1701. def __rmul__(self, i):
  1702. """
  1703. Return (self * i), that is string multiple concatenation,
  1704. element-wise.
  1705. See Also
  1706. --------
  1707. multiply
  1708. """
  1709. return asarray(multiply(self, i))
  1710. def __mod__(self, i):
  1711. """
  1712. Return (self % i), that is pre-Python 2.6 string formatting
  1713. (interpolation), element-wise for a pair of array_likes of `bytes_`
  1714. or `str_`.
  1715. See Also
  1716. --------
  1717. mod
  1718. """
  1719. return asarray(mod(self, i))
  1720. def __rmod__(self, other):
  1721. return NotImplemented
  1722. def argsort(self, axis=-1, kind=None, order=None):
  1723. """
  1724. Return the indices that sort the array lexicographically.
  1725. For full documentation see `numpy.argsort`, for which this method is
  1726. in fact merely a "thin wrapper."
  1727. Examples
  1728. --------
  1729. >>> c = np.array(['a1b c', '1b ca', 'b ca1', 'Ca1b'], 'S5')
  1730. >>> c = c.view(np.chararray); c
  1731. chararray(['a1b c', '1b ca', 'b ca1', 'Ca1b'],
  1732. dtype='|S5')
  1733. >>> c[c.argsort()]
  1734. chararray(['1b ca', 'Ca1b', 'a1b c', 'b ca1'],
  1735. dtype='|S5')
  1736. """
  1737. return self.__array__().argsort(axis, kind, order)
  1738. argsort.__doc__ = ndarray.argsort.__doc__
  1739. def capitalize(self):
  1740. """
  1741. Return a copy of `self` with only the first character of each element
  1742. capitalized.
  1743. See Also
  1744. --------
  1745. char.capitalize
  1746. """
  1747. return asarray(capitalize(self))
  1748. def center(self, width, fillchar=' '):
  1749. """
  1750. Return a copy of `self` with its elements centered in a
  1751. string of length `width`.
  1752. See Also
  1753. --------
  1754. center
  1755. """
  1756. return asarray(center(self, width, fillchar))
  1757. def count(self, sub, start=0, end=None):
  1758. """
  1759. Returns an array with the number of non-overlapping occurrences of
  1760. substring `sub` in the range [`start`, `end`].
  1761. See Also
  1762. --------
  1763. char.count
  1764. """
  1765. return count(self, sub, start, end)
  1766. def decode(self, encoding=None, errors=None):
  1767. """
  1768. Calls ``bytes.decode`` element-wise.
  1769. See Also
  1770. --------
  1771. char.decode
  1772. """
  1773. return decode(self, encoding, errors)
  1774. def encode(self, encoding=None, errors=None):
  1775. """
  1776. Calls `str.encode` element-wise.
  1777. See Also
  1778. --------
  1779. char.encode
  1780. """
  1781. return encode(self, encoding, errors)
  1782. def endswith(self, suffix, start=0, end=None):
  1783. """
  1784. Returns a boolean array which is `True` where the string element
  1785. in `self` ends with `suffix`, otherwise `False`.
  1786. See Also
  1787. --------
  1788. char.endswith
  1789. """
  1790. return endswith(self, suffix, start, end)
  1791. def expandtabs(self, tabsize=8):
  1792. """
  1793. Return a copy of each string element where all tab characters are
  1794. replaced by one or more spaces.
  1795. See Also
  1796. --------
  1797. char.expandtabs
  1798. """
  1799. return asarray(expandtabs(self, tabsize))
  1800. def find(self, sub, start=0, end=None):
  1801. """
  1802. For each element, return the lowest index in the string where
  1803. substring `sub` is found.
  1804. See Also
  1805. --------
  1806. char.find
  1807. """
  1808. return find(self, sub, start, end)
  1809. def index(self, sub, start=0, end=None):
  1810. """
  1811. Like `find`, but raises `ValueError` when the substring is not found.
  1812. See Also
  1813. --------
  1814. char.index
  1815. """
  1816. return index(self, sub, start, end)
  1817. def isalnum(self):
  1818. """
  1819. Returns true for each element if all characters in the string
  1820. are alphanumeric and there is at least one character, false
  1821. otherwise.
  1822. See Also
  1823. --------
  1824. char.isalnum
  1825. """
  1826. return isalnum(self)
  1827. def isalpha(self):
  1828. """
  1829. Returns true for each element if all characters in the string
  1830. are alphabetic and there is at least one character, false
  1831. otherwise.
  1832. See Also
  1833. --------
  1834. char.isalpha
  1835. """
  1836. return isalpha(self)
  1837. def isdigit(self):
  1838. """
  1839. Returns true for each element if all characters in the string are
  1840. digits and there is at least one character, false otherwise.
  1841. See Also
  1842. --------
  1843. char.isdigit
  1844. """
  1845. return isdigit(self)
  1846. def islower(self):
  1847. """
  1848. Returns true for each element if all cased characters in the
  1849. string are lowercase and there is at least one cased character,
  1850. false otherwise.
  1851. See Also
  1852. --------
  1853. char.islower
  1854. """
  1855. return islower(self)
  1856. def isspace(self):
  1857. """
  1858. Returns true for each element if there are only whitespace
  1859. characters in the string and there is at least one character,
  1860. false otherwise.
  1861. See Also
  1862. --------
  1863. char.isspace
  1864. """
  1865. return isspace(self)
  1866. def istitle(self):
  1867. """
  1868. Returns true for each element if the element is a titlecased
  1869. string and there is at least one character, false otherwise.
  1870. See Also
  1871. --------
  1872. char.istitle
  1873. """
  1874. return istitle(self)
  1875. def isupper(self):
  1876. """
  1877. Returns true for each element if all cased characters in the
  1878. string are uppercase and there is at least one character, false
  1879. otherwise.
  1880. See Also
  1881. --------
  1882. char.isupper
  1883. """
  1884. return isupper(self)
  1885. def join(self, seq):
  1886. """
  1887. Return a string which is the concatenation of the strings in the
  1888. sequence `seq`.
  1889. See Also
  1890. --------
  1891. char.join
  1892. """
  1893. return join(self, seq)
  1894. def ljust(self, width, fillchar=' '):
  1895. """
  1896. Return an array with the elements of `self` left-justified in a
  1897. string of length `width`.
  1898. See Also
  1899. --------
  1900. char.ljust
  1901. """
  1902. return asarray(ljust(self, width, fillchar))
  1903. def lower(self):
  1904. """
  1905. Return an array with the elements of `self` converted to
  1906. lowercase.
  1907. See Also
  1908. --------
  1909. char.lower
  1910. """
  1911. return asarray(lower(self))
  1912. def lstrip(self, chars=None):
  1913. """
  1914. For each element in `self`, return a copy with the leading characters
  1915. removed.
  1916. See Also
  1917. --------
  1918. char.lstrip
  1919. """
  1920. return asarray(lstrip(self, chars))
  1921. def partition(self, sep):
  1922. """
  1923. Partition each element in `self` around `sep`.
  1924. See Also
  1925. --------
  1926. partition
  1927. """
  1928. return asarray(partition(self, sep))
  1929. def replace(self, old, new, count=None):
  1930. """
  1931. For each element in `self`, return a copy of the string with all
  1932. occurrences of substring `old` replaced by `new`.
  1933. See Also
  1934. --------
  1935. char.replace
  1936. """
  1937. return asarray(replace(self, old, new, count))
  1938. def rfind(self, sub, start=0, end=None):
  1939. """
  1940. For each element in `self`, return the highest index in the string
  1941. where substring `sub` is found, such that `sub` is contained
  1942. within [`start`, `end`].
  1943. See Also
  1944. --------
  1945. char.rfind
  1946. """
  1947. return rfind(self, sub, start, end)
  1948. def rindex(self, sub, start=0, end=None):
  1949. """
  1950. Like `rfind`, but raises `ValueError` when the substring `sub` is
  1951. not found.
  1952. See Also
  1953. --------
  1954. char.rindex
  1955. """
  1956. return rindex(self, sub, start, end)
  1957. def rjust(self, width, fillchar=' '):
  1958. """
  1959. Return an array with the elements of `self`
  1960. right-justified in a string of length `width`.
  1961. See Also
  1962. --------
  1963. char.rjust
  1964. """
  1965. return asarray(rjust(self, width, fillchar))
  1966. def rpartition(self, sep):
  1967. """
  1968. Partition each element in `self` around `sep`.
  1969. See Also
  1970. --------
  1971. rpartition
  1972. """
  1973. return asarray(rpartition(self, sep))
  1974. def rsplit(self, sep=None, maxsplit=None):
  1975. """
  1976. For each element in `self`, return a list of the words in
  1977. the string, using `sep` as the delimiter string.
  1978. See Also
  1979. --------
  1980. char.rsplit
  1981. """
  1982. return rsplit(self, sep, maxsplit)
  1983. def rstrip(self, chars=None):
  1984. """
  1985. For each element in `self`, return a copy with the trailing
  1986. characters removed.
  1987. See Also
  1988. --------
  1989. char.rstrip
  1990. """
  1991. return asarray(rstrip(self, chars))
  1992. def split(self, sep=None, maxsplit=None):
  1993. """
  1994. For each element in `self`, return a list of the words in the
  1995. string, using `sep` as the delimiter string.
  1996. See Also
  1997. --------
  1998. char.split
  1999. """
  2000. return split(self, sep, maxsplit)
  2001. def splitlines(self, keepends=None):
  2002. """
  2003. For each element in `self`, return a list of the lines in the
  2004. element, breaking at line boundaries.
  2005. See Also
  2006. --------
  2007. char.splitlines
  2008. """
  2009. return splitlines(self, keepends)
  2010. def startswith(self, prefix, start=0, end=None):
  2011. """
  2012. Returns a boolean array which is `True` where the string element
  2013. in `self` starts with `prefix`, otherwise `False`.
  2014. See Also
  2015. --------
  2016. char.startswith
  2017. """
  2018. return startswith(self, prefix, start, end)
  2019. def strip(self, chars=None):
  2020. """
  2021. For each element in `self`, return a copy with the leading and
  2022. trailing characters removed.
  2023. See Also
  2024. --------
  2025. char.strip
  2026. """
  2027. return asarray(strip(self, chars))
  2028. def swapcase(self):
  2029. """
  2030. For each element in `self`, return a copy of the string with
  2031. uppercase characters converted to lowercase and vice versa.
  2032. See Also
  2033. --------
  2034. char.swapcase
  2035. """
  2036. return asarray(swapcase(self))
  2037. def title(self):
  2038. """
  2039. For each element in `self`, return a titlecased version of the
  2040. string: words start with uppercase characters, all remaining cased
  2041. characters are lowercase.
  2042. See Also
  2043. --------
  2044. char.title
  2045. """
  2046. return asarray(title(self))
  2047. def translate(self, table, deletechars=None):
  2048. """
  2049. For each element in `self`, return a copy of the string where
  2050. all characters occurring in the optional argument
  2051. `deletechars` are removed, and the remaining characters have
  2052. been mapped through the given translation table.
  2053. See Also
  2054. --------
  2055. char.translate
  2056. """
  2057. return asarray(translate(self, table, deletechars))
  2058. def upper(self):
  2059. """
  2060. Return an array with the elements of `self` converted to
  2061. uppercase.
  2062. See Also
  2063. --------
  2064. char.upper
  2065. """
  2066. return asarray(upper(self))
  2067. def zfill(self, width):
  2068. """
  2069. Return the numeric string left-filled with zeros in a string of
  2070. length `width`.
  2071. See Also
  2072. --------
  2073. char.zfill
  2074. """
  2075. return asarray(zfill(self, width))
  2076. def isnumeric(self):
  2077. """
  2078. For each element in `self`, return True if there are only
  2079. numeric characters in the element.
  2080. See Also
  2081. --------
  2082. char.isnumeric
  2083. """
  2084. return isnumeric(self)
  2085. def isdecimal(self):
  2086. """
  2087. For each element in `self`, return True if there are only
  2088. decimal characters in the element.
  2089. See Also
  2090. --------
  2091. char.isdecimal
  2092. """
  2093. return isdecimal(self)
  2094. @set_module("numpy.char")
  2095. def array(obj, itemsize=None, copy=True, unicode=None, order=None):
  2096. """
  2097. Create a `chararray`.
  2098. .. note::
  2099. This class is provided for numarray backward-compatibility.
  2100. New code (not concerned with numarray compatibility) should use
  2101. arrays of type `bytes_` or `str_` and use the free functions
  2102. in :mod:`numpy.char <numpy.core.defchararray>` for fast
  2103. vectorized string operations instead.
  2104. Versus a regular NumPy array of type `str` or `unicode`, this
  2105. class adds the following functionality:
  2106. 1) values automatically have whitespace removed from the end
  2107. when indexed
  2108. 2) comparison operators automatically remove whitespace from the
  2109. end when comparing values
  2110. 3) vectorized string operations are provided as methods
  2111. (e.g. `str.endswith`) and infix operators (e.g. ``+, *, %``)
  2112. Parameters
  2113. ----------
  2114. obj : array of str or unicode-like
  2115. itemsize : int, optional
  2116. `itemsize` is the number of characters per scalar in the
  2117. resulting array. If `itemsize` is None, and `obj` is an
  2118. object array or a Python list, the `itemsize` will be
  2119. automatically determined. If `itemsize` is provided and `obj`
  2120. is of type str or unicode, then the `obj` string will be
  2121. chunked into `itemsize` pieces.
  2122. copy : bool, optional
  2123. If true (default), then the object is copied. Otherwise, a copy
  2124. will only be made if __array__ returns a copy, if obj is a
  2125. nested sequence, or if a copy is needed to satisfy any of the other
  2126. requirements (`itemsize`, unicode, `order`, etc.).
  2127. unicode : bool, optional
  2128. When true, the resulting `chararray` can contain Unicode
  2129. characters, when false only 8-bit characters. If unicode is
  2130. None and `obj` is one of the following:
  2131. - a `chararray`,
  2132. - an ndarray of type `str` or `unicode`
  2133. - a Python str or unicode object,
  2134. then the unicode setting of the output array will be
  2135. automatically determined.
  2136. order : {'C', 'F', 'A'}, optional
  2137. Specify the order of the array. If order is 'C' (default), then the
  2138. array will be in C-contiguous order (last-index varies the
  2139. fastest). If order is 'F', then the returned array
  2140. will be in Fortran-contiguous order (first-index varies the
  2141. fastest). If order is 'A', then the returned array may
  2142. be in any order (either C-, Fortran-contiguous, or even
  2143. discontiguous).
  2144. """
  2145. if isinstance(obj, (bytes, str)):
  2146. if unicode is None:
  2147. if isinstance(obj, str):
  2148. unicode = True
  2149. else:
  2150. unicode = False
  2151. if itemsize is None:
  2152. itemsize = len(obj)
  2153. shape = len(obj) // itemsize
  2154. return chararray(shape, itemsize=itemsize, unicode=unicode,
  2155. buffer=obj, order=order)
  2156. if isinstance(obj, (list, tuple)):
  2157. obj = numpy.asarray(obj)
  2158. if isinstance(obj, ndarray) and issubclass(obj.dtype.type, character):
  2159. # If we just have a vanilla chararray, create a chararray
  2160. # view around it.
  2161. if not isinstance(obj, chararray):
  2162. obj = obj.view(chararray)
  2163. if itemsize is None:
  2164. itemsize = obj.itemsize
  2165. # itemsize is in 8-bit chars, so for Unicode, we need
  2166. # to divide by the size of a single Unicode character,
  2167. # which for NumPy is always 4
  2168. if issubclass(obj.dtype.type, str_):
  2169. itemsize //= 4
  2170. if unicode is None:
  2171. if issubclass(obj.dtype.type, str_):
  2172. unicode = True
  2173. else:
  2174. unicode = False
  2175. if unicode:
  2176. dtype = str_
  2177. else:
  2178. dtype = bytes_
  2179. if order is not None:
  2180. obj = numpy.asarray(obj, order=order)
  2181. if (copy or
  2182. (itemsize != obj.itemsize) or
  2183. (not unicode and isinstance(obj, str_)) or
  2184. (unicode and isinstance(obj, bytes_))):
  2185. obj = obj.astype((dtype, int(itemsize)))
  2186. return obj
  2187. if isinstance(obj, ndarray) and issubclass(obj.dtype.type, object):
  2188. if itemsize is None:
  2189. # Since no itemsize was specified, convert the input array to
  2190. # a list so the ndarray constructor will automatically
  2191. # determine the itemsize for us.
  2192. obj = obj.tolist()
  2193. # Fall through to the default case
  2194. if unicode:
  2195. dtype = str_
  2196. else:
  2197. dtype = bytes_
  2198. if itemsize is None:
  2199. val = narray(obj, dtype=dtype, order=order, subok=True)
  2200. else:
  2201. val = narray(obj, dtype=(dtype, itemsize), order=order, subok=True)
  2202. return val.view(chararray)
  2203. @set_module("numpy.char")
  2204. def asarray(obj, itemsize=None, unicode=None, order=None):
  2205. """
  2206. Convert the input to a `chararray`, copying the data only if
  2207. necessary.
  2208. Versus a regular NumPy array of type `str` or `unicode`, this
  2209. class adds the following functionality:
  2210. 1) values automatically have whitespace removed from the end
  2211. when indexed
  2212. 2) comparison operators automatically remove whitespace from the
  2213. end when comparing values
  2214. 3) vectorized string operations are provided as methods
  2215. (e.g. `str.endswith`) and infix operators (e.g. ``+``, ``*``,``%``)
  2216. Parameters
  2217. ----------
  2218. obj : array of str or unicode-like
  2219. itemsize : int, optional
  2220. `itemsize` is the number of characters per scalar in the
  2221. resulting array. If `itemsize` is None, and `obj` is an
  2222. object array or a Python list, the `itemsize` will be
  2223. automatically determined. If `itemsize` is provided and `obj`
  2224. is of type str or unicode, then the `obj` string will be
  2225. chunked into `itemsize` pieces.
  2226. unicode : bool, optional
  2227. When true, the resulting `chararray` can contain Unicode
  2228. characters, when false only 8-bit characters. If unicode is
  2229. None and `obj` is one of the following:
  2230. - a `chararray`,
  2231. - an ndarray of type `str` or 'unicode`
  2232. - a Python str or unicode object,
  2233. then the unicode setting of the output array will be
  2234. automatically determined.
  2235. order : {'C', 'F'}, optional
  2236. Specify the order of the array. If order is 'C' (default), then the
  2237. array will be in C-contiguous order (last-index varies the
  2238. fastest). If order is 'F', then the returned array
  2239. will be in Fortran-contiguous order (first-index varies the
  2240. fastest).
  2241. """
  2242. return array(obj, itemsize, copy=False,
  2243. unicode=unicode, order=order)