Open In App

Python program for removing i-th character from a string

Last Updated : 14 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given the string, we have to remove the ith indexed character from the string. In any string, indexing always start from 0. Suppose we have a string geeks then its indexing will be as –

g e e k s
0 1 2 3 4

Examples :

Input : Geek
        i = 1
Output : Gek

Input : Peter 
        i = 4
Output : Pete

Approach 1 : From the given string, i-th indexed element has to be removed. So, Split the string into two halves, before indexed character and after indexed character. Return the merged string. Below is the implementation of above approach : 

Python




# Python3 program for removing i-th
# indexed character from a string
  
# Removes character at index i
  
  
def remove(string, i):
  
    # Characters before the i-th indexed
    # is stored in a variable a
    a = string[: i]
  
    # Characters after the nth indexed
    # is stored in a variable b
    b = string[i + 1:]
  
    # Returning string after removing
    # nth indexed character.
    return a + b
  
  
# Driver Code
if __name__ == '__main__':
  
    string = "geeksFORgeeks"
  
    # Remove nth index element
    i = 5
  
    # Print the new string
    print(remove(string, i))


Output

geeksORgeeks

Time Complexity: O(n) where n is the length of the string.
Auxiliary Space: O(n) where n is the length of the string.

Approach 2 : The idea is to use string replace in Python 

Python




# Python3 program for removing i-th
# indexed character from a string
  
# Removes character at index i
  
  
def remove(string, i):
  
    for j in range(len(string)):
        if j == i:
            string = string.replace(string[i], "", 1)
    return string
  
  
# Driver Code
if __name__ == '__main__':
  
    string = "geeksFORgeeks"
  
    # Remove nth index element
    i = 5
  
    # Print the new string
    print(remove(string, i))


Output

geeksORgeeks

Time Complexity: O(n) where n is the length of the string. This is because the function performs a single loop through the string and calls the replace function once.
Auxiliary Space: O(1) because the function uses only a few variables and no additional data structures are created.

Approach 3 : Using list(),pop() and join() methods

Python3




# Python3 program for removing i-th
# indexed character from a string
  
# Removes character at index i
  
  
def remove(string, i):
    if i > len(string):
        return string
    a = list(string)
    a.pop(i)
    return "".join(a)
  
  
# Driver Code
if __name__ == '__main__':
  
    string = "geeksFORgeeks"
  
    # Remove nth index element
    i = 2
  
    # Print the new string
    print(remove(string, i))


Output

geksFORgeeks

Time Complexity: O(n) where n is the length of the string

Auxiliary Space: O(n) where n is the length of the string 

Approach 4: Using enumerate, join

Python3




def remove(string, i):
  return "".join()
  
print(remove("geeksforgeeks",2))


Output

geksforgeeks

The above approach uses a list comprehension to create a new list of characters from the original string, but excluding the i-th character. It iterates over the original string and for each character, it checks if the index of the character (j) is not equal to the specified index (i). If it is not equal, the character is included in the new list. Then, the join method is used to combine the characters of the new list into a single string. This approach is more concise than the previous ones, as it combines the steps of creating a new list and joining it into a single line of code.

Time complexity: O(n), where n is the length of the input string. This is because the function involves iterating through all the characters in the string and creating a new string by concatenating the characters that are not being removed.
Auxiliary Space: O(n) because it involves creating a new string with the same length as the input string.

Approach 5: Using the re module and f-string 

  • Import the re module
  • pattern = f”(^.{{{i}}})(.)” Create a regular expression pattern that matches the character along with the substring before it. ^ matches the start of the string, {i} specifies the index of the character to be removed,
  • re.sub(pattern, r”\1″, string) is used to substitute the matched pattern with the captured substring before the given index.

Python3




# Python3 program for removing i-th
# indexed character from a string
  
# Removes character at index i
  
import re
  
def remove(string, i):
    pattern = f"(^.{{{i}}})(.)"
    return re.sub(pattern, r"\1", string)
  
# Driver Code
if __name__ == '__main__':
    string = "geeksFORgeeks"
    #i-th index to be removed
    i = 5
    #string after removal of i-th index
    print(remove(string, i))


Output

geeksORgeeks

Time Complexity: O(N)  where n is the length of the input string as it iterates over all characters in the string to find the matching pattern.

Space Complexity: O(N) where n is the length of the input string as we creates a new string with the same length



Similar Reads

Program for removing i-th character from a string
Given a string S along with an integer i. Then your task is to remove ith character from S. Examples: Input: S = Hello World!, i = 7Output: Hello orld!Explanation: The Xth character is W and after removing it S becomes Hello orld! Input: S = GFG, i = 1Output: GGExplanation: It can be verified that after removing 1st character the string S will be G
5 min read
Removing newline character from string in Python
Many times, while working with Python strings, we can have a problem in which we have a huge amount of data and we need to perform preprocessing of a certain kind. This can also be removing stray newline characters in strings. Let's discuss certain ways in which this task can be performed. Remove Newline character from String in Python Here, we wil
3 min read
Check if frequency of character in one string is a factor or multiple of frequency of same character in other string
Given two strings, the task is to check whether the frequencies of a character(for each character) in one string are multiple or a factor in another string. If it is, then output "YES", otherwise output "NO". Examples: Input: s1 = "aabccd", s2 = "bbbaaaacc" Output: YES Frequency of 'a' in s1 and s2 are 2 and 4 respectively, and 2 is a factor of 4 F
6 min read
Count of index pairs (i, j) such that string after deleting ith character is equal to string after deleting jth character
Given a string str of N characters, the task is to calculate the count of valid unordered pairs of (i, j) such that the string after deleting ith character is equal to the string after deleting the jth character. Examples: Input: str = "aabb"Output: 2Explanation: The string after deletion of 1st element is "abb" and the string after deletion of 2nd
6 min read
Minimize the length of string by removing occurrence of only one character
Given a string str containing only lowercase alphabets, the task is to minimize the length of the string after performing the following operation: Delete all occurrences of any one character from this string. Examples: Input: str = "abccderccwq"Output: 7character 'c' will be deleted since it has maximum occurrence. Input: str = "dddded"Output: 1Exp
4 min read
Lexicographically smallest string formed by removing at most one character
Given a string str, the task is to find the lexicographically smallest string that can be formed by removing at most one character from the given string. Examples: Input: str = "abcda" Output: abca One can remove 'd' to get "abca" which is the lexicographically smallest string possible. Input: str = "aaa' Output: aa Approach: Traverse the string an
4 min read
Lexicographically smallest subsequence possible by removing a character from given string
Given a string S of length N, the task is to find the lexicographically smallest subsequence of length (N - 1), i.e. by removing a single character from the given string. Examples: Input: S = "geeksforgeeks"Output: "eeksforgeeks"Explanation: Lexicographically smallest subsequence possible is "eeksforgeeks". Input: S = "zxvsjas"Output: "xvsjas"Expla
8 min read
Find the winner of game of repeatedly removing the first character to empty given string
Given a positive integer N, representing the count of players playing the game and an array of strings arr[], consisting of the numeric strings made up of digits from the range ['1', 'N']. Considering ith player is assigned with the string arr[i], the task is to find the winner of the game when all N players play the game optimally as per the follo
7 min read
Check if given string can be made Palindrome by removing only single type of character
Given a string S, the task is to whether a string can be made palindrome after removing the occurrences of the same character, any number of times Examples: Input: S = "abczdzacb" Output: Yes Explanation: Remove first and second occurrence of character 'a', string S becomes "bczdzcb", which is a palindrome . Input: S = "madem"Output: No Approach: T
7 min read
Minimum operations to make a numeric string palindrome by removing at most 2 unique character occurrences
Given numeric string str, the task is to find the minimum operations needed to make the string palindrome. An operation is defined as: Select one character and remove any of its occurrences.For all the operations, the number of unique characters chosen must be less than 2 Examples: Input: str = "11221"Output: 1Explanation: Select '1' and remove any
11 min read
Practice Tags :