DEV Community

Sreeram
Sreeram

Posted on

How to Replace Character at Nth Index in Python String

Often, Python developers need to replace a character at a specific position(nth index) in string in Python. While it is easy to do this in JavaScript, it can be tricky to do the same in Python. This is because strings are immutable in Python, that is, once they are defined, they cannot be modified. On the other hand, JavaScript strings are mutable arrays. So you can directly replace a character using the array name and index.

For example, let us say you want to replace letter 'e' in string 'pen' with letter 'i'. You can quickly do this in JavaScript as shown below.

var temp = 'pen';
n= 1
temp[n] = 'i'; // index of 1st letter is 0, 2nd letter is 1,...
console.log(temp); // prints pin
Enter fullscreen mode Exit fullscreen mode

Let us try to do the same in Python. Here is what we get.

>>> temp='pen'
>>> n = 1
>>> temp[n]='i'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
Enter fullscreen mode Exit fullscreen mode

As you can see, Python throws an error. So how do we solve this problem?

The trick is to create a new string with the new character at the desired index. There are several ways to do this. Let's look at a couple of easy ones.

1. Using Slicing

In this approach, we slice the original string till the nth index, add the new character, followed by the slice of the original string after nth index.

temp = 'pen'
n = 1
new_temp = temp[: n] + 'i' + temp[n + 1:]
print(new_temp)      # displays pin
Enter fullscreen mode Exit fullscreen mode

2. Using List & Join

In this approach, we use list() function to convert the string into a list. Then we replace the desired character using its index. Then we convert python list back into string using join() function.

temp = 'pen'
n = 1
x = list(temp)       # x = ['p','e','n']
x[n] = 'i'
new_temp = "".join(x)
print new_temp       # output is pin
Enter fullscreen mode Exit fullscreen mode

Please note, in both the above cases, the string after replacement of character is different from the original string. In Python, you can completely redefine a string but cannot modify its parts.

Of course, there are a few other ways to do this but we have covered a couple of simple ones. Please feel free to share how you do it.

Top comments (0)