The Wayback Machine - https://web.archive.org/web/20240914143959/https://www.geeksforgeeks.org/ways-to-remove-ith-character-from-string-in-python/
Open In App

How to Remove Letters From a String in Python

Last Updated : 28 Aug, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

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
Get the Outer Product of an array with vector of letters using NumPy in Python
In this article let's see how to get the outer product of an array with a vector of letters in Python. numpy.outer() method The numpy.outer() method is used to get the outer product of an array with a vector of elements in Python. A matrix is the outer product of two coordinate vectors in linear algebra. The outer product of two vectors with dimens
4 min read
MoviePy – Text with moving Letters
In this article we will see how we can move the letters of the text clip MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Video is formed by the frames, combination of frames creates a video each frame is an individual image. VideoClip is the base class for all the other video clips
4 min read
Remove Special Characters from String Python
The generic problem faced by the programmers is to remove unwanted characters from a string using Python. But sometimes the requirement is way above and demands the removal of more than 1 character, but a list of such malicious characters. These can be in the form of special characters for reconstructing valid passwords and many other applications
6 min read
How to remove string accents using Python 3?
String accents are special string characters adapted from languages of other accents. In this article, we are going to remove ascents from a string. Examples: Input: orčpžsíáýd Output: orcpzsiayd Input: stävänger Output: stavanger We can remove accents from the string by using a Python module called Unidecode. This module consists of a method that
2 min read
How to remove numbers from string in Python - Pandas?
In this article, let's see how to remove numbers from string in Pandas. Currently, we will be using only the .csv file for demonstration purposes, but the process is the same for other types of files. The function read_csv() is used to read CSV files. Syntax: for the method 'replace()': str.replace(old, new) Here str. replace() will return a string
2 min read
Remove All Duplicates from a Given String in Python
We are given a string and we need to remove all duplicates from it. What will be the output if the order of character matters? Examples: Input : geeksforgeeks Output : geksfor This problem has an existing solution please refer to Remove all duplicates from a given string. Method 1: [GFGTABS] Python from collections import OrderedDict # Function to
3 min read
Remove \xa0 from a string in Python
In Python, \xa0 represents a non-breaking space (Unicode character U+00A0). We use this in HTML parsing, web scraping, or working with text where the non-breaking space is used to prevent line breaks between words. Understanding \xa0 (Non-Breaking Space)The \xa0 character is the Unicode representation for a non-breaking space (NBSP), which is diffe
4 min read
Remove all duplicate adjacent characters from a string using Stack
Given a string, str, the task is to remove all the duplicate adjacent characters from the given string. Examples: Input: str= “azxxzy”Output: ay Removal of "xx" modifies the string to “azzy”. Now, the removal of "zz" modifies the string to “ay”. Since the string “ay” doesn't contain duplicates, the output is ay. Input: "aaccdd"Output: Empty String
6 min read
Remove character in a String except Alphabet
Given a string consisting of alphabets and other characters, remove all the characters other than alphabets and print the string so formed. Example Input: str = "$Gee*k;s..fo, r'Ge^eks?" Output: GeeksforGeeks Program to Remove characters in a string except alphabetsBelow are the steps and methods by which we can remove all characters other than alp
2 min read
Python Remove Duplicates from a List
The job is simple. We need to take a list, with duplicate elements in it and generate another list that only contains the element without the duplicates in them. Examples: Input : [2, 4, 10, 20, 5, 2, 20, 4] Output : [2, 4, 10, 20, 5] Input : [28, 42, 28, 16, 90, 42, 42, 28] Output : [28, 42, 16, 90] We can use not in on list to find out the duplic
3 min read
Python groupby method to remove all consecutive duplicates
Given a string S, remove all the consecutive duplicates. Examples: Input : aaaaabbbbbb Output : ab Input : geeksforgeeks Output : geksforgeks Input : aabccba Output : abcba We have existing solution for this problem please refer Remove all consecutive duplicates from the string link. We can solve this problem in python quickly using itertools.group
2 min read
Python | Remove empty tuples from a list
In this article, we will see how can we remove an empty tuple from a given list of tuples. We will find various ways, in which we can perform this task of removing tuples using various methods and ways in Python. Examples: Input : tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('',''),()]Output : [('ram', '15',
8 min read
Python | Remove all duplicates words from a given sentence
Given a sentence containing n words/strings. Remove all duplicates words/strings which are similar to each others. Examples: Input : Geeks for Geeks Output : Geeks for Input : Python is great and Java is also great Output : is also Java Python and great We can solve this problem quickly using python Counter() method. Approach is very simple. 1) Spl
7 min read
Python | Remove and print every third from list until it becomes empty
Given a list of numbers, Your task is to remove and print every third number from a list of numbers until the list becomes empty. Examples: Input : [10, 20, 30, 40, 50, 60, 70, 80, 90] Output : 30 60 90 40 80 50 20 70 10 Explanation: The first third element encountered is 30, after 30 we start the count from 40 for the next third element which is 6
4 min read
Ways to remove particular List element in Python
List is an important container and is used almost in every code of day-day programming as well as web development. The more it is used, more is the required to master it and hence knowledge of its operations is necessary. Let's see the different ways of removing particular list elements. Method #1 : Using remove() remove() can perform the task of r
6 min read
Python | Remove empty strings from list of strings
In many scenarios, we encounter the issue of getting an empty string in a huge amount of data and handling that sometimes becomes a tedious task. Let's discuss certain way-outs to remove empty strings from list of strings. Method #1: Using remove() This particular method is quite naive and not recommended use, but is indeed a method to perform this
7 min read
Python | Remove all values from a list present in other list
Sometimes we need to perform the operation of removing all the items from the lists that are present in another list, i.e we are given some of the invalid numbers in one list which need to be get ridden from the original list. Let's discuss various ways How to remove the elements of a list from another list in Python. Illustration: Input: List one
10 min read
Python | Remove item from dictionary when key is unknown
Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. Let's discuss the various ways to remove items from the dictionary when key is unknown. Method #1 : Using n
6 min read
Python | Remove consecutive duplicates from list
In Python, we generally wish to remove the duplicate elements, but sometimes for several specific usecases, we require to have remove just the elements repeated in succession. This is a quite easy task and having a shorthand for it can be useful. Let's discuss certain ways in which this task can be performed. Method #1 : Using groupby() + list comp
4 min read
Python | Remove all sublists outside the given range
Given, list of lists and a range, the task is to traverse each sub-list and remove sublists containing elements falling out of given range. Examples: Input : left= 10, right = 17, list = [[0, 1.2, 3.4, 18.1, 10.1], [10.3, 12.4, 15, 17, 16, 11], [100, 10, 9.2, 11, 13, 17.1], ] Output: [[10.3, 12.4, 15, 17, 16, 11]] Input : left= 1, right = 9, list =
3 min read
Python | os.remove() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have
3 min read
Python | Remove square brackets from list
Sometimes, while working with displaying the contents of list, the square brackets, both opening and closing are undesired. For this when we need to print the whole list without accessing the elements for loops, we require a method to perform this. Let's discuss a shorthand by which this task can be performed. Method 1: Using str() + list slicing T
5 min read
Python | Remove Consecutive tuple according to key
Sometimes, while working with Python list, we can have a problem in which we can have a list of tuples and we wish to remove them basis of first element of tuple to avoid it's consecutive duplication. Let's discuss certain way in which this problem can be solved. Method : Using groupby() + itemgetter() + next() This task can be performed using comb
5 min read
Matplotlib.axes.Axes.remove() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. matplotlib.axes.Axes.remove() Function The Axes.re
1 min read
Python - Remove Key from Dictionary List
Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove a specific key from a dictionary list. This kind of problem is very common and has application in almost all domains including day-day programming and web development domain. Let's discuss certain ways in which this task can be performed. Method #1 :
7 min read
Python - Remove empty value types in dictionaries list
Sometimes, while working with Python dictionaries, we require to remove all the values that are virtually Null, i.e does not hold any meaningful value and are to be removed before processing data, this can be an empty string, empty list, dictionary, or even 0. This has applications in data preprocessing. Let us discuss certain ways in which this ta
7 min read
Python - Remove Dictionary Key Words
Sometimes, while working with Python strings, we can have a problem in which we need to remove all the words from a string that is part of the key of the dictionary. This problem can have applications in domains such as web development and day-day programming. Let's discuss certain ways in which this task can be performed. Method #1: Using split()
7 min read
Matplotlib.artist.Artist.remove() in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Artist class contains Abstract base class for objects that render into a FigureCanvas. All visible elements in a figure are subclasses of Artist. Matplotlib.artist.Artist.remove() Method The remove() method in artist module of matplotlib library is
1 min read
Matplotlib.axis.Axis.remove() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. Matplotlib.axis.Axis.remove() Function The Axis.remove() function in axis module of matplotlib library is used to remove the arti
1 min read
Practice Tags :