Python program to change character of a string using given index

PythonServer Side ProgrammingProgramming

Suppose we have a string s, an index i and a character c. We have to replace the ith character of s using c. Now in Python, strings are immutable in nature. We cannot write a statement like s[i] = c, it will raise an error [TypeError: 'str' object does not support item assignment]

So, if the input is like s = "python", i = 3, c = 'P', then the output will be "pytPon"

To solve this, we will follow these steps −

  • left := s[from index 0 to i]

  • right := s[from index i+1 to end]

  • return left concatenate c concatenate right


Let us see the following implementation to get better understanding

def solve(s, i, c):
   left = s[:i]
   right = s[i+1:]
   return left + c + right

s = "python"
i = 3
c = 'P'
print(solve(s, i, c))


python, 3, 'P'


Published on 11-Oct-2021 10:55:39