How to Remove Letters From a String in Python
Strings are data types used to represent text/characters. In this article, we present different methods for the problem of removing the ith character from a string and talk about possible solutions that can be employed in achieving them using Python.
Input: 'Beginner123For123Beginner'
Output: w3wiki
Explanation: In This, we have removed the '123' character from a string.
Remove Characters From a String in Python
These are the following methods using which we can remove letters from a string in Python:
- Using str.replace()
- Using translate()
- Using recursion
- Using Native Method
- Using slice + concatenation
- Using str.join()
- Using bytearray
- Using removeprefix()
Remove Characters From a String Using replace()
str.replace() can be used to replace all the occurrences of the desired character. It can also be used to perform the task of character removal from a string as we can replace the particular index with empty char, and hence solve the issue.
Python3
# Initializing String test_str = "w3wiki" # 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) |
The string after removal of i'th character( doesn't work) : GksForGks The string after removal of i'th character(works) : GeekForBeginner
Time Complexity: O(n)
Space Complexity: O(n)
Drawback: The major drawback of using replace() is that it fails in cases where there are 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.
Remove the Specific Character from the String using Translate()
This method provides a strong mechanism to remove characters from a string. In this method, we removed 123 from w3wiki using string.translate().
Python3
str = 'Beginner123For123Beginner' print ( str .translate({ ord (i): None for i in '123' })) |
Output
w3wiki
Time Complexity: O(n)
Space Complexity: O(m)
Remove the Specific Character from the String Using Recursion
To remove the ith character from a string using recursion, you can define a recursive function that takes in the string and the index to be removed as arguments. The function will check if the index is equal to 0, in this 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.
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 = "w3wiki" 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: GeksForBeginner
Time Complexity: O(n)
Space Complexity: O(n)
Remove Letters From a 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 = "w3wiki" # 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) |
The string after removal of i'th character : GeksForBeginner
Time Complexity: O(n)
Space Complexity: O(n), where n is length of string.
Remove the ith Character from the String Using Slice
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 = "w3wiki" # 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) |
The string after removal of i'th character : GeksForBeginner
Time Complexity: O(n)
Space Complexity: O(n)
Remove the ith Character from the String Using str.join()
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 = "w3wiki" # 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) |
The string after removal of i'th character : GeksForBeginner
Time Complexity: O(n)
Space Complexity: O(n)
Delete Letters From a String in Python Using bytearray
Define the function remove_char(s, i) that takes a string s and an integer i as input. And then 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() and 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)
Space Complexity: O(n)
Remove Letters From a String Using removeprefix()
removeprefix() removes the prefix and returns the rest of the string. We can remove letters from a string for any specific index by dividing the string into two halves such that the letter that we wanted to remove comes in the prefix of any of the two partition and then we can apply the method to remove the letter.
Python3
#initializing the string s = "w3wiki" #if you wanted to remove "G" of 0th index s1 = s.removeprefix( "G" ) #if you wanted to remove "f" s2 = s[: 5 ] + s[ 5 :].removeprefix( "f" ) print (s1) print (s2) |
Output:
eeksforBeginner
BeginnerorBeginner
Time Complexity: O(n)
Space Complexity: O(n)
Contact Us