Skip to content

Python replace character in a string by index | Example code

A simple way to replace a character in a string by index in python is the slicing method.

Python replace character in a string with index Example

Simple example code replaces the character at a Specific Position. Where in the example we are taking a string, and replace the character at index=5 with X.

string = 'Python'
position = 5
new_character = 'X'

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

Output:

Python replace character in a string by index

Replace Character at a given Position in a String using List

First, convert the string to a list, then replace the item at the given index with a new character, and then join the list items to the string.

string = 'EyeHunte'
position = 7
new_character = 's'

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

print(string)

Output: EyeHunts

Replace multiple char using index positions in a string with the same character

string = 'Python'
list_of_indexes = [1, 3, 5]
new_character = 'Z'
res = ''

# Replace characters at index positions in list
for i in list_of_indexes:
    string = string[:i] + new_character + string[i+1:]

print(string)

Output: PZtZoZ

Replace characters at multiple index positions in a string with different characters

string = 'Python'
cr = {1: 'X',
      3: 'Y',
      5: 'Z'}

res = ''

# Replace multiple characters with different replacement characters
for index, replacement in cr.items():
    string = string[:index] + cr[index] + string[index + 1:]

print(string)

Output: PXtYoZ

Do comment if you have any doubts and suggestions on this Python char index example code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

5 thoughts on “Python replace character in a string by index | Example code”

  1. “Python replace character in a string with index Example” (seems not work)

    Proposed modification: (for position>0)
    string = string[position-1:] + new_character + string[:position+1]

      1. It seems to work for the example … So, my assumption was incorrect. (Still I find it strange that you can use an invalid index to define a slice.)

Leave a Reply

Your email address will not be published. Required fields are marked *