Open In App

Replace a String character at given index in Python

Last Updated : 16 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, strings are immutable, meaning they cannot be directly modified. We need to create a new string using various methods to replace a character at a specific index.

Using slicing

Slicing is one of the most efficient ways to replace a character at a specific index.

Python
s = "hello"

idx = 1
replacement = "a"
res = s[:idx] + replacement + s[idx+1:]
print(res)

Output
hallo

Explanation:

  • The string is split into two parts: everything before the target index (text[:index]) and everything after (text[index+1:]).
  • The replacement character is inserted between these slices.
  • This method is simple, efficient, and works well for small or large strings.

Using list conversion

Converting the string to a list allows us to modify its characters directly before converting it back.

Python
s = "hello"

idx = 1
replacement = "a"

a = list(s)
a[idx] = replacement

res = ''.join(b)
print(res)

Output
hallo

Explanation:

  • The string is converted to a list because lists are mutable.
  • We modify the character at the target index and then rejoin the list into a string.
  • This method is slightly less efficient but useful for multiple modifications.

Using regular expressions

Regular expressions can be used to replace a character at a specific position by matching patterns.

Python
import re

s = "hello"

idx = 1
replacement = "a"

# Create a pattern to match the character at the specific index
pattern = f"^(.{{{idx}}})."

res = re.sub(pattern, rf"\1{replacement}", s)
print(res)

Output
hallo

Explanation:

  • The pattern matches the character at the desired index using lookbehind.
  • The re.sub() method replaces the matched character with the specified replacement.
  • This method is powerful but less efficient and more complex for simple replacements.

Using a manual loop

We can iterate through the string and build a new one, replacing the character at the given index.

Python
s = "hello"
idx = 1
replacement = "a"
res = ""

for i in range(len(s)):
    if i == idx:
        res += replacement
    else:
        res += s[i]

print(res)

Output
hallo

Explanation:

  • The loop iterates through the string and appends characters to a new string.
  • At the target index, the replacement character is added instead.

Related Articles:



Next Article
Practice Tags :

Similar Reads