Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

NumPy: replace() function

numpy.core.defchararray.replace() function

For each element in a given array numpy.core.defchararray.replace() function returns a copy of the string with all occurrences of substring old replaced by new.
Calls str.replace element-wise.

Version: 1.15.0

Syntax:

numpy.core.defchararray.replace(a, old, new, count=None)

Parameter:

Name Description Required /
Optional
a Given array-like of string or unicode Required
old, new Given old or new string or unicode Required
count If the optional argument count is given, only the first count occurrences are replaced. Optional

Return value:

out : ndarray - Output array of str or unicode, depending on input type

Note:

The 'chararray' class exists for backwards compatibility with Numarray, it is not recommended for new development. Starting from numpy 1.4, if one needs arrays of strings, it is recommended to use arrays of 'dtype' 'object_', 'string_' or 'unicode_', and use the free functions in the 'numpy.char' module for fast vectorized string operations.

Some methods will only be available if the corresponding string method is available in your version of Python.

The preferred alias for 'defchararray' is 'numpy.char'.

Example-1: numpy.replace() function

>>> import numpy as np
>>> x = np.char.replace('The quick brown fox', 'fox', 'wolf')
>>> x
array('The quick brown wolf', dtype='<U20')

Pictorial Presentation:

NumPy String operation: replace() function

Example-2: numpy.replace() function

>>> import numpy as np
>>> x = np.char.replace('The quick fox brown fox', 'fox', 'wolf', count=0)
>>> x
array('The quick fox brown fox', dtype='<U23')

Pictorial Presentation:

NumPy String operation: replace() function

Example-3: numpy.replace() function

>>> import numpy as np
>>> x = np.char.replace('The quick fox brown fox', 'fox', 'wolf', count=1)
>>> x
array('The quick wolf brown fox', dtype='<U24')

Pictorial Presentation:

NumPy String operation: replace() function

Example-4: numpy.replace() function

>>> import numpy as np
>>> x = np.char.replace('The quick fox brown fox', 'fox', 'wolf', count=2)
>>> x
array('The quick wolf brown wolf', dtype='<U25')

Pictorial Presentation:

NumPy String operation: replace() function

Python - NumPy Code Editor:

Previous: partition()
Next: rjust()