Five Ways To Remove Characters From A String In Python

In this article, we are going to see different ways to remove characters from a string.

String in python

The string is an in-built class i.e. data type in python which is a sequence of characters, enclosed by double/single/triple inverted comma, an array of Unicode characters (i.e. you can have a string in any language in the world, not just English).

Strings in Python are immutable; once created you cannot change it. When you update the string, the interpreter creates a new string and the garbage collector removes the previous string if you haven't removed it. Unlike other programming languages, there’s no character data type in python.

A character can be a string of length 1. What you write inside an inverted comma is called a literal. As strings are immutables. You cannot update/delete any specific character. This will lead to error.

For example, Below operations are not permitted.

del str[2]

str[2] ='B'

In [1]:
 # creating string in python 

if __name__ == "__main__":
   # How string are created.
   string1 = "This is String 'in double inverted'"
   string2 = 'This is Also a "string" '
   string3 = """Multiline string should be used inside three times double/single inverted comma"""
   print(f"String 1: {string1}")
   print(f"String 2: {string2}")
   print(f"String 3: {string3}")
String 1: This is String 'in double inverted'
String 2: This is Also a "string" 
String 3: Multiline string should be used inside three times double/single inverted comma

Now, Let's discuss ways to remove a charecter from string.

Remove Character from String using Brute Force method

In the example below, we create a new string, and loop through it. If we encounter the required character, we simply don’t include it in our new string. To find if the character is present, we can either do a direct check or if know the position of the character, we can do an index check.

Let us do an example.

In [2]:
if __name__ =="__main__":
   str1 = "Python" # string created.
   result = "" # this will hold our result.
   # remove P from str1
   for i in str1:
           result+= i
   print(result) #output ython
   # Index based.
   # remove character at 3rd index.
   result =""
   for i in range(len(str1)):
       if( i !=3 ):
   print(result )


Strings are immutable in python. So in step result += i, we are creating length(str1) -1 a new string. This will consume extra memory.

Remove Character from String using Python Replace method

syntax: stringName.replace(old character, no of characters to remove)

3rd argument is an option, if not specified it will remove all characters

In [3]:
if __name__ =="__main__":
   str1 = "Python Programming"
   # remove one or all occurrences of n (character) using replace method.
   print("String after replced: "+str1.replace('n','',2))
   print("Original String: "+str1) # .replace returns a new string, not updates the original string.
String after replced: Pytho Programmig
Original String: Python Programming

Remove Character from String using Slice method

This method is useful if you know the index of the element that should be removed. In Python, we can access part of string using [ ].

[] operator

In [4]:
if __name__ == "__main__":
   # str1[start index: end index(Not excluded): gap number]
   print(str1[::-1])  # will print string in reverse order
   print(str1[::2]) # if nothing given , it will skip every alternate character
   print(str1[:3:-1]) # skip the first 4 characters and print the remaining characters in reverse order
In [5]:
if __name__=="__main__":
   str1 = "Python"
   print ("Original string: " + str1)
   # remove at index 2
   str1 = str1[:2]+str1[3:]
   # as in range [a:b] b is excluded and index counting starts from left to right.
   print ("String after removal of character: " + str1)
Original string: Python
String after removal of character: Pyhon

Remove Character from String Using Python Join method

Syntax: Join method :

lis1 = ['P','Y','T','O','N']

s = "=="

s = s.join(lis1)


output :

P==Y==T==O==N <class 'str'>

As we see above, join method is used to build a string from a list. In the above example, we built a string from the list of characters. To join these characters, we used '=='.

The result is returned as a new string.

In [6]:
str1 = "Python"
print("Original string: " + str1)
# Removing char at index 2
# using join() + list comprehension
result_str = ''.join([str1[i] for i in range(len(str1)) if i != 2])
# quite the same as the brute force method. 
# As join is a pure concatenating method.
print ("String after removal of character: " + result_str)
Original string: Python
String after removal of character: Pyhon

Remove Character from String using Python Translate method

Syntax : Translate method


mapping – a dictionary(key-value pair) having mapping between two characters...

translate() returns a a modified string using translation mappings or table.


In [7]:
if __name__ =="__main__":
   print(str1.translate({ord(i): None for i in 'PYTHON'}))