The Wayback Machine - https://web.archive.org/web/20230508072134/https://www.geeksforgeeks.org/ways-to-remove-ith-character-from-string-in-python/
Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Ways to remove i’th character from string in Python

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

This article presents one such problem of removing the ith character from a string and talks about possible solutions that can be employed in achieving them using Python.

Remove the ith character from the string using the native method

In this method, one just has to run a Python loop and append the characters as they come and build a new string from the existing one except when the index is i. 

Python3




test_str = "GeeksForGeeks"
 
# Removing char at pos 3
new_str = ""
 
for i in range(len(test_str)):
    if i != 2:
        new_str = new_str + test_str[i]
 
# Printing string after removal
print ("The string after removal of i'th character : " + new_str)

Output

The string after removal of i'th character : GeksForGeeks

Time complexity: O(n)
Auxiliary Space: O(n), where n is length of string.

Remove the ith character from the string using str.replace()

The str.replace() can possibly be used for performing the task of removal as we can replace the particular index with empty char, and hence solve the issue. 

Drawback: The major drawback of this approach is that it fails in case there as duplicates in a string that match the char at pos. i. replace() replaces all the occurrences of a particular character and hence would replace all the occurrences of all the characters at pos i. We can still sometimes use this function if the replacing character occurs for 1st time in the string. 

Python3




# Initializing String
test_str = "GeeksForGeeks"
 
# Removing char at pos 3
# using replace
new_str = test_str.replace('e', '')
 
# Printing string after removal
# removes all occurrences of 'e'
print ("The string after removal of i'th character( doesn't work) : " + new_str)
 
# Removing 1st occurrence of s, i.e 5th pos.
# if we wish to remove it.
new_str = test_str.replace('s', '', 1)
 
# Printing string after removal
# removes first occurrences of s
print ("The string after removal of i'th character(works) : " + new_str)

Output

The string after removal of i'th character( doesn't work) : GksForGks
The string after removal of i'th character(works) : GeekForGeeks

Remove the ith character from the string using slice + concatenation

One can use string slice and slice the string before the pos i, and slice after the pos i. Then using string concatenation of both, ith character can appear to be deleted from the string. 

Python3




# Initializing String
test_str = "GeeksForGeeks"
 
# Removing char at pos 3
# using slice + concatenation
new_str = test_str[:2] + test_str[3:]
 
# Printing string after removal
# removes ele. at 3rd index
print ("The string after removal of i'th character : " + new_str)

Output

The string after removal of i'th character : GeksForGeeks

Remove the ith character from the string using str.join() and list comprehension

In this method, each element of a string is first converted as each element of the list, and then each of them is joined to form a string except the specified index. 

Python3




# Initializing String
test_str = "GeeksForGeeks"
 
# Removing char at pos 3
# using join() + list comprehension
new_str = ''.join([test_str[i] for i in range(len(test_str)) if i != 2])
 
# Printing string after removal
# removes ele. at 3rd index
print ("The string after removal of i'th character : " + new_str)

Output

The string after removal of i'th character : GeksForGeeks

Remove the specific character from the string using translate()

In this method, we removed 123 from Geeksforgeeks using string.translate(). 

Python3




str = 'Geeks123For123Geeks'
  
print(str.translate({ord(i): None for i in '123'}))

Output

GeeksForGeeks

Using Recursion:

To use recursion to remove the ith character from a string, you can define a recursive function that takes in the string and the index to be removed as arguments. The function can check if the index is equal to 0, in which case it returns the string with the first character removed. If the index is not 0, the function can return the first character of the string concatenated with the result of calling the function again on the string with the index decremented by 1.

Here is an example of how you could implement this approach:

Python3




def remove_ith_character(s, i):
    # Base case: if index is 0, return string with first character removed
    if i == 0:
        return s[1:]
     
    # Recursive case: return first character concatenated with result of calling function on string with index decremented by 1
    return s[0] + remove_ith_character(s[1:], i - 1)
 
# Test the function
test_str = "GeeksForGeeks"
new_str = remove_ith_character(test_str, 2)
print("The string after removal of ith character:", new_str)
#This code is contributed by Edula Vinay Kumar Reddy

Output

The string after removal of ith character: GeksForGeeks

In terms of time complexity, this approach has a time complexity of O(n) where n is the length of the string, because the function makes a single recursive call for each character in the string.

In terms of space complexity, this approach has a space complexity of O(n) because the function makes a recursive call for each character in the string, and each call requires space on the call stack.

Using bytearray():

Approach:

Define the function remove_char(s, i) that takes a string s and an integer i as input.
Convert the input string s to a bytearray using bytearray(s, ‘utf-8’).
Delete the i’th element from the bytearray using del b[i].
Convert the modified bytearray back to a string using b.decode().
Return the modified string.

Python3




def remove_char(s, i):
    b = bytearray(s, 'utf-8')
    del b[i]
    return b.decode()
 
# Example usage
s = "hello world"
i = 4
s = remove_char(s, i)
print(s)

Output

hell world

Time Complexity: O(n), where n is the length of the string
Space Complexity: O(n), where n is the length of the string (due to creation of new bytearray)


My Personal Notes arrow_drop_up
Last Updated : 30 Mar, 2023
Like Article
Save Article
Similar Reads
Related Tutorials