defchararray.py 71 KB

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