Remove Character in a String at a Specific Index in Python

Last Updated : 03 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Removing a character from a string at a specific index is a common task when working with strings and because strings in Python are immutable we need to create a new string without the character at the specified index. String slicing is the simplest and most efficient way to remove a character at a specific index.

Python
s1 = "Python"

# Index of the character to remove
idx = 3
# Remove character at the specified index using slicing
res = s1[:idx] + s1[idx + 1:]
print(res) 

Output
Pyton

Using List Conversion

Another way is to convert the string into a list, remove the character and then join the list back into a string.

Python
s1 = "Python"

# Index of the character to remove
idx = 3
# Convert string to a list

li = list(s1)
# Remove the character at the specified index

li.pop(idx)
# Join the list back into a string
res = ''.join(li)
print(res)   

Output
Pyton

Converting the string into a list allows direct modification using list methods like .pop() and the .join() method merges the list back into a string.

Using a Loop (Manual Method)

A loop can be used to construct the string if someone prefers to iterate manually by skipping the character at the specified index.

Python
s1 = "Python"

# Index of the character to remove
idx = 3

# Use a loop to build a new string without the character
res = ''.join(char for i, char in enumerate(s1) if i != idx)
print(res)    

Output
Pyton

The enumerate() function iterates through the string with both index and character and the conditional statement (if i != index) skips the character at the specified index.

Using Regular Expressions

To remove a character from a string at a specific index using regular expressions (regex), you can use Python's re module.

Python
import re
s1 = "Python"

# Index of the character to remove
idx = 3

# Use regex to replace the character at the specified index
pattern = re.escape(s1[idx])
res = re.sub(pattern, "", s1, count=1)
print(res)  

Output
Pyton

The re.escape() function ensures that special characters are handled correctly and the re.sub() replaces the first occurrence of the character with an empty string.


Next Article

Similar Reads