For each element in ``a``, return a copy of the string with occurrences of substring ``old`` replaced by ``new``. Parameters ---------- a : array_like, with ``bytes_`` or ``str_`` dtype old, new : array_like, with ``bytes_`` or ``str_`` dtype count : array_like, with
(a, old, new, count=-1)
| 1289 | @set_module("numpy.strings") |
| 1290 | @array_function_dispatch(_replace_dispatcher) |
| 1291 | def replace(a, old, new, count=-1): |
| 1292 | """ |
| 1293 | For each element in ``a``, return a copy of the string with |
| 1294 | occurrences of substring ``old`` replaced by ``new``. |
| 1295 | |
| 1296 | Parameters |
| 1297 | ---------- |
| 1298 | a : array_like, with ``bytes_`` or ``str_`` dtype |
| 1299 | |
| 1300 | old, new : array_like, with ``bytes_`` or ``str_`` dtype |
| 1301 | |
| 1302 | count : array_like, with ``int_`` dtype |
| 1303 | If the optional argument ``count`` is given, only the first |
| 1304 | ``count`` occurrences are replaced. |
| 1305 | |
| 1306 | Returns |
| 1307 | ------- |
| 1308 | out : ndarray |
| 1309 | Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype, |
| 1310 | depending on input types |
| 1311 | |
| 1312 | See Also |
| 1313 | -------- |
| 1314 | str.replace |
| 1315 | |
| 1316 | Examples |
| 1317 | -------- |
| 1318 | >>> import numpy as np |
| 1319 | >>> a = np.array(["That is a mango", "Monkeys eat mangos"]) |
| 1320 | >>> np.strings.replace(a, 'mango', 'banana') |
| 1321 | array(['That is a banana', 'Monkeys eat bananas'], dtype='<U19') |
| 1322 | |
| 1323 | >>> a = np.array(["The dish is fresh", "This is it"]) |
| 1324 | >>> np.strings.replace(a, 'is', 'was') |
| 1325 | array(['The dwash was fresh', 'Thwas was it'], dtype='<U19') |
| 1326 | |
| 1327 | """ |
| 1328 | count = np.asanyarray(count) |
| 1329 | if not np.issubdtype(count.dtype, np.integer): |
| 1330 | raise TypeError(f"unsupported type {count.dtype} for operand 'count'") |
| 1331 | |
| 1332 | arr = np.asanyarray(a) |
| 1333 | old_dtype = getattr(old, 'dtype', None) |
| 1334 | old = np.asanyarray(old) |
| 1335 | new_dtype = getattr(new, 'dtype', None) |
| 1336 | new = np.asanyarray(new) |
| 1337 | |
| 1338 | if np.result_type(arr, old, new).char == "T": |
| 1339 | return _replace(arr, old, new, count) |
| 1340 | |
| 1341 | a_dt = arr.dtype |
| 1342 | old = old.astype(old_dtype or a_dt, copy=False) |
| 1343 | new = new.astype(new_dtype or a_dt, copy=False) |
| 1344 | max_int64 = np.iinfo(np.int64).max |
| 1345 | counts = _count_ufunc(arr, old, 0, max_int64) |
| 1346 | counts = np.where(count < 0, counts, np.minimum(counts, count)) |
| 1347 | buffersizes = str_len(arr) + counts * (str_len(new) - str_len(old)) |
| 1348 | out_dtype = f"{arr.dtype.char}{buffersizes.max()}" |