for example

a='mama' a= a.replace(a[-1],'x') print a 

Why it turns out not mamx, a mxmx?

  • one
    a[-1] - returns the character 'a', which is passed as an argument to the function replace and its call becomes equivalent to replace ('a', 'x') - Specter

2 answers 2

The replace function takes 2 arguments as input:

1) What character should be replaced;

2) What symbol should be replaced.

The function is applied to the string. You extract a slice (i.e., a substring) from the string 'mama'. The result of this slice is the character 'a'. Then you apply the replace function to the entire line. Those. ask python in the string 'mama' to find all the characters 'a' and replace them with 'x'.

    Here is how to get 'mamx'

     >>> a = 'mama' >>> b = a[:-1] + 'x' >>> print b mamx