Open In App

How to Remove Letters From a String in Python

Last Updated : 28 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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: 'Geeks123For123Geeks'
Output: GeeksForGeeks
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:

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 = "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

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 GeeksforGeeks using string.translate()

Python3




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


Output

GeeksForGeeks

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 = "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

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 = "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)
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 = "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

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 = "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

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="GeeksforGeeks"
 
#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:

eeksforGeeks
GeeksorGeeks

Time Complexity: O(n)
Space Complexity: O(n)



Previous Article
Next Article

Similar Reads

Python | Remove all characters except letters and numbers
Given a string, the task is to remove all the characters except numbers and alphabets. String manipulation is a very important task in a day to day coding and web development. Most of the requests and responses in HTTP queries are in the form of Python strings with sometimes some useless data which we need to remove. Remove all characters except le
4 min read
Python Program that Displays the Letters that are in the First String but not in the Second
Python program to display the letters in the first string but not in the second can be done by taking two sets and subtracting them. As sets support the difference operator, one set could contain the letters of the first string and another set could contain the letters of the second string and when subtracted we could obtain the desired result. Exa
5 min read
Python | Ways to sort letters of string alphabetically
Given a string of letters, write a python program to sort the given string in an alphabetical order. Example: Input : PYTHON Output : HNOPTY Input : Geeks Output : eeGksNaive Method to sort letters of string alphabetically Here we are converting the string into list and then finally sorting the entire list alphabet wise. C/C++ Code s ="GEEKSFO
2 min read
Python | Insert value after each k letters in given list of string
Given a list of string, write a Python program to Insert some letter after each k letters in given list of strings. As we know inserting element in a list is quite common, but sometimes we need to operate on list of strings by considering each letter and insert some repeated elements some fixed frequency. Let's see how to achieve this task using Py
5 min read
Python | First N letters string construction
Sometimes, rather than initializing the empty string, we need to initialize a string in a different way, vis., we may need to initialize a string with 1st N characters in English alphabets. This can have applications in competitive Programming. Let's discuss certain ways in which this task can be performed. Method #1: Using join() + list comprehens
4 min read
Python program to verify that a string only contains letters, numbers, underscores and dashes
Given a string, we have to find whether the string contains any letters, numbers, underscores, and dashes or not. It is usually used for verifying username and password validity. For example, the user has a string for the username of a person and the user doesn't want the username to have any special characters such as @, $, etc. Prerequisite: Regu
4 min read
Python program to check if lowercase letters exist in a string
Given a string, the task is to write a Python program to check if the string has lowercase letters or not. Examples: Input: "Live life to the fullest" Output: true Input: "LIVE LIFE TO THe FULLEST" Output: true Input: "LIVE LIFE TO THE FULLEST" Output: false Methods 1#: Using islower() It Returns true if all cased characters in the string are lower
5 min read
Python program to calculate the number of digits and letters in a string
Given a string, containing digits and letters, the task is to write a Python program to calculate the number of digits and letters in a string. Example:Input: string = "geeks2for3geeks" Output: total digits = 2 and total letters = 13 Input: string = "python1234" Output: total digits = 4 and total letters = 6 Input: string = "co2mpu1te10rs" Output:
7 min read
Regex in Python to put spaces between words starting with capital letters
Given an array of characters, which is basically a sentence. However, there is no space between different words and the first letter of every word is in uppercase. You need to print this sentence after the following amendments: Put a single space between these words. Convert the uppercase letters to lowercase Examples: Input : BruceWayneIsBatmanOut
2 min read
Python regex to find sequences of one upper case letter followed by lower case letters
Write a Python Program to find sequences of one upper case letter followed by lower case letters. If found, print 'Yes', otherwise 'No'. Examples: Input : GeeksOutput : YesInput : geeksforgeeksOutput : NoPython regex to find sequences of one upper case letter followed by lower case lettersUsing re.search() To check if the sequence of one upper case
2 min read
Practice Tags :