8.8 Replacing Substrings

A common text manipulation is to locate a substring and replace its value. Method replace takes two substrings. It searches a string for the substring in its first argument and replaces each occurrence with the substring in its second argument. The method returns a new string containing the results. Let’s replace tab characters with commas:

In [1]: values = '1	2	3	4	5'

In [2]: values.replace('	', ',')
Out[2]: '1,2,3,4,5'

Method replace can receive an optional third argument specifying the maximum number of replacements to perform.

tick mark Self Check

  1. (IPython Session) Replace the spaces in the string '1 2 3 4 5' with ' --> '.
    Answer:

    In [1]: '1 2 3 4 5'.replace(' ', ' --> ')
    Out[1]: '1 --> 2 --> 3 --> 4 --> 5'
    
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.6.77