In this article, we will discuss how to replace a character in a string at a specific position. Then we will also see how to replace multiple characters in a string by index positions.


Table of Contents

Use Python string slicing to replace nth character in a string

To replace a character at index position n in a string, split the string into three sections: characters before nth character, the nth character, and the characters after the nth characters. Then join back the sliced pieces to create a new string but use instead of using the nth character, use the replacement character. For example,

sample_str = "This is a sample string"

n = 3
replacement = 'C'

# Replace character at nth index position
sample_str = sample_str[0:n] + replacement + sample_str[n+1: ]

print(sample_str)

Output:

ThiC is a sample string

In the above example, we replaced the character at index position 3 in the string. For that, we sliced the string into three pieces i.e.

  1. Characters from index position 0 to 2.
  2. Character at index position 3
  3. Characters from index position 3 till the end of string.

Then we joined the above slices, but instead of using the character at position 3, we used the replacement character ‘C’.

Python function to replace a character in a string by index position

The slicing approach is good to replace the nth character in a string. But what if somebody tries to replace a character at an index that doesn’t exist? That means if the given index position for replacement is greater than the number of characters in a string, then it can give unexpected results. Therefore we should always check if the given nth position is in the range or not.

To avoid this kind of error, we have created a function,

def replace_char_at_index(org_str, index, replacement):
    ''' Replace character at index in string org_str with the
    given replacement character.'''
    new_str = org_str
    if index < len(org_str):
        new_str = org_str[0:index] + replacement + org_str[index + 1:]
    return new_str

Now let’s use this function to replace nth character in a string,

sample_str = "This is a sample string"

# Replace character at 3rd index position
sample_str = replace_char_at_index(sample_str, 3, 'C')

print(sample_str)

Output:

ThiC is a sample string

Let’s try to replace a character at index position, which is out of bounds,

sample_str = "This is a sample string"

# Replace character at 50th index position
sample_str = replace_char_at_index(sample_str, 50, 'C')

print(sample_str)

Output:

This is a sample string

Python: Replace characters at multiple index positions in a string with the same character

We have few index positions in a list, and we want to replace all the characters at these index positions. To do that, we will iterate over all the index positions in the list. And for each index, replace the character at that index by slicing the string,

sample_str = "This is a sample string"

# Index positions
list_of_indexes = [1, 3, 5]

# Replace characters at index positions in list
for index in list_of_indexes:
    sample_str = replace_char_at_index(sample_str, index, 'C')

print(sample_str)

Output:

TCiC Cs a sample string

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

In the above example, we replace all the characters at given positions by the same replacement characters. But it might be possible that in some scenarios, we want to replace them with different replacement characters.
Suppose we have a dictionary that contains the index positions and the replacement characters as key-value pairs. We want to replace all the characters at these index positions by their corresponding replacement character. To do that, we will iterate over all the key-value pairs in the dictionary. And for each key, replace the character at that index position by the character in the value field. For example,

sample_str = "This is a sample string"

char_to_replace = {1: 'X',
                   3: 'Y',
                   5: 'Z'}

# Replace multiple characters with different replacement characters
for index, replacement in char_to_replace.items():
    sample_str = replace_char_at_index(sample_str, index, replacement)

print(sample_str)

Output:

TXiY Zs a sample string

Summary

We can use the string slicing in python to replace the characters in a string by their index positions.

Join a list of 2000+ Programmers for latest Tips & Tutorials