Python String – Replace character at Specific Position

Python – Replace Character at Specific Index in String

To replace a character with a given character at a specified index, you can use python string slicing as shown below:

string = string[:position] + character + string[position+1:]

where character is the new character that has to be replaced with and position is the index at which we are replacing the character.

Example 1: Replace Character at a given Position in a String using String Slicing

In the following example, we will take a string, and replace character at index=6 with e.

Python Program

string = 'pythonhxamples'
position = 6
new_character = 'e'

string = string[:position] + new_character + string[position+1:]
print(string)
Run

Output

pythonexamples

Example 2: Replace Character at a given Position in a String using List

In the following example, we will take a string, and replace character at index=6 with e. To do this, we shall first convert the string to a list, then replace the item at given index with new character, and then join the list items to string.

Python Program

string = 'pythonhxamples'
position = 6
new_character = 'e'

temp = list(string)
temp[position] = new_character
string = "".join(temp)

print(string)
Run

Output

pythonexamples

Summary

In this tutorial of Python Examples, we learned how to replace a character at specific index in a string with a new character.

Related Tutorials