Python - Replace Character at Specific Index in String


Python - Replace Character at Specific Index in String

To replace a character at a specific index in a string, Python provides an efficient way using slicing, or you can use alternative methods like converting the string into a list. Since strings are immutable in Python, these methods effectively create a new string.

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

Here:

  • string[:position]: Substring up to but not including the specified index.
  • character: The new character to be inserted.
  • string[position+1:]: Substring from the next character after the index to the end.

Examples

1. Replace character at a given index using slicing

In the following example, we replace the 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)

Explanation:

  1. Initially, string = 'pythonhxamples'.
  2. string[:position]: Extracts the substring 'python'.
  3. new_character = 'e': The character to be inserted.
  4. string[position+1:]: Extracts the substring 'xamples' starting from index 7.
  5. The final string is formed by concatenating these parts: 'python' + 'e' + 'xamples'.

Output:

pythonexamples

2. Replace character at a given index using a list

This example demonstrates replacing a character by converting the string into a list, modifying the element, and then joining the list back into a string.

Python Program

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

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

print(string)

Explanation:

  1. The string is converted into a list using list(string), so it can be modified.
  2. temp[position] = new_character: Replaces the element at index 6 with 'e'.
  3. "".join(temp): Combines the list back into a string.
  4. The final string is 'pythonexamples'.

Output:

pythonexamples

3. Replace multiple characters at specific indices

You can replace multiple characters in a string at specified indices by looping through the indices.

Python Program

string = 'pythonhxamples'
replacements = {6: 'e', 8: 'E'}

string = ''.join(
    replacements[i] if i in replacements else char 
    for i, char in enumerate(string)
)

print(string)

Explanation:

  1. The dictionary replacements maps indices to the characters to be replaced.
  2. The enumerate(string) function iterates over the string with index and character.
  3. replacements[i] if i in replacements: Replaces the character if the index is in the dictionary; otherwise, keeps the original character.
  4. The result is joined into a new string using ''.join().

Output:

pythonexEmples

4. Replace character at a specific index in a multiline string

This example shows replacing a character in a specific line of a multiline string.

Python Program

string = """Python examples
are really helpful.
Let's learn Python."""

line_number = 1
position = 5
new_character = 'E'

lines = string.split('\n')
lines[line_number] = (
    lines[line_number][:position] + new_character + lines[line_number][position+1:]
)
string = '\n'.join(lines)

print(string)

Explanation:

  1. The string is split into lines using split('\n').
  2. lines[line_number][:position] + new_character + lines[line_number][position+1:]: Replaces the character at the specified position in the selected line.
  3. '\n'.join(lines): Combines the lines back into a multiline string.

Output:

Python examples
are rEally helpful.
Let's learn Python.

Summary

In this tutorial, we explored multiple ways to replace a character at a specific index in a string:

  • Using string slicing.
  • Converting the string to a list.
  • Replacing multiple characters at specified indices.
  • Replacing characters in multiline strings.

Each method is useful depending on the complexity and requirements of the task.


Python Libraries