Strings | The find(), replace(), list(), and join() methods

Using the find() method.

>>> name = 'xxxDANxxxDEVxxx'
>>> where = name.find('DEV')
>>> where
9
>>> name = name[:9] + 'DUM' + name[(where + 3):]
>>> name
'xxxDANxxxDUMxxx'

Using the replace() method.

>>> name = 'xxxDANxxxDEVxxx'
>>> name.replace('DEV', 'DUM')
'xxxDANxxxDUMxxx'

Using list() and join() methods.

>>> name = 'xxxDANxxxDEVxxx'
>>> L = list(name)
>>> L
['x', 'x', 'x', 'D', 'A', 'N', 'x', 'x', 'x', 'D', 'E', 'V', 'x', 'x', 'x']
>>> L[10] = 'U'
>>> L[11] = 'M'
>>> name = ''.join(L)
>>> name
'xxxDANxxxDUMxxx'

You might ask why there is '' (empty string) before join(). Take a look below.

>>> 'aa'.join(L)
'xaaxaaxaaDaaAaaNaaxaaxaaxaaDaaUaaMaaxaaxaax'

Leave a Reply