-4

The string in python behaves similar to list. Then why can't we change value using assignment operator.

Example:

name = 'whatever'

why can't we do assignment like name[0] = 'k'

If we need to make a change like this, how can we do that?

Edwin van Mierlo
  • 2,398
  • 1
  • 10
  • 19
user9461026
  • 51
  • 1
  • 8
  • 2
    because strings are immutable, you need to rebuild the string like `name = 'k' + name[1:]` but use a list if you want a mutable structure – Chris_Rands Jun 28 '18 at 08:33

2 Answers2

2

you could do something like this:

s = "abcde"     # create string
l = list(s)     # convert to list
l[2] = "X"      # modify character
"".join(l)      # join to string again
Felix
  • 6,131
  • 4
  • 24
  • 44
-1

A string in Python is immutable. You can use something like .replace() or iterate through the string and create a new one.

For example:

name = 'whatever'
name.replace("w", "k")