Python - Replace Character at Specific Index in String
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.
Examples
1. Replace character at a given index in a string using 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)
Output
pythonexamples
2. Replace character at a given index 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)
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.