How do i remove characters from text in python?

Sometimes we want to remove all occurrences of a character from a string. There are two common ways to achieve this.

Python Remove Character from String

  1. Using string replace() function
  2. Using string translate() function

Python Remove Character from String using replace()

We can use string replace() function to replace a character with a new character. If we provide an empty string as the second argument, then the character will get removed from the string. Note that the string is immutable in Python, so this function will return a new string and the original string will remain unchanged.

s = 'abc12321cba'

print(s.replace('a', ''))

Output: bc12321cb

Python Remove Character from String using translate()

Python string translate() function replace each character in the string using the given translation table. We have to specify the Unicode code point for the character and ‘None’ as a replacement to remove it from the result string. We can use ord() function to get the Unicode code point of a character.

s = 'abc12321cba'

print(s.translate({ord('a'): None}))

Output: bc12321cb If you want to replace multiple characters, that can be done easily using an iterator. Let’s see how to remove characters ‘a’, ‘b’ and ‘c’ from a string.

s = 'abc12321cba'

print(s.translate({ord(i): None for i in 'abc'}))

Output: 12321

Removing Spaces from a String

s = ' 1 2 3 4 '
print(s.replace(' ', ''))  # 1234
print(s.translate({ord(i): None for i in ' '}))  # 1234

Python Remove newline from String

s = 'ab\ncd\nef'
print(s.replace('\n', ''))
print(s.translate({ord('\n'): None}))

Remove substring from string

String replace() function arguments is string. Let’s see how to remove a word from a string.

s = 'ab12abc34ba'
print(s.replace('ab', ''))

Output: 12c34ba

Remove specified number of times

We can also pass a third parameter in replace() function to specify the number of times replacement should be performed.

s = 'abababab'
print(s.replace('a', 'A', 2))

Output: AbAbabab

You can checkout complete python script and more Python examples from our GitHub Repository.

The following methods are used to remove a specific character from a string in Python.

  1. By using Naive method
  2. By using replace() function
  3. By using slice and concatenation
  4. By using join() and list comprehension
  5. By using translate() method

Note that the string is immutable in Python. So the original string remains unchanged and a new string is returned by these methods.


1. Removing a Character from String using the Naive method

In this method, we have to run a loop and append the characters and build a new string from the existing characters except when the index is n. (where n is the index of the character to be removed)

input_str = "DivasDwivedi"
  
# Printing original string  
print ("Original string: " + input_str) 
  
result_str = "" 
  
for i in range(0, len(input_str)): 
    if i != 3: 
        result_str = result_str + input_str[i] 
  
# Printing string after removal   
print ("String after removal of i'th character : " + result_str)

Output:

Original string: DivasDwivedi
String after removal of i’th character : DivsDwivedi


2. Removal of Character from a String using replace() Method

str = "Engineering"
  

print ("Original string: " + str) 
  

res_str = str.replace('e', '') 
  

# removes all occurrences of 'e' 
print ("The string after removal of character: " + res_str) 
  
# Removing 1st occurrence of e 

res_str = str.replace('e', '', 1) 
   
print ("The string after removal of character: " + res_str) 

Output:

Original string: Engineering
The string after removal of character: Enginring
The string after removal of character: Enginering


3. Removal of Character from a String using Slicing and Concatenation

str = "Engineering"
  

print ("Original string: " + str) 
  
# Removing char at pos 3 
# using slice + concatenation 
res_str = str[:2] +  str[3:] 
  

print ("String after removal of character: " + res_str) 

Output:

Original string: Engineering
String after removal of character: Enineering


4. Removal of Character from a String using join() method and list comprehension

In this technique, every element of the string is converted to an equivalent element of a list, after which each of them is joined to form a string excluding the particular character to be removed.

str = "Engineering"
  

print ("Original string: " + str) 
  
# Removing char at index 2 
# using join() + list comprehension 
res_str = ''.join([str[i] for i in range(len(str)) if i != 2]) 
  

print ("String after removal of character: " + res_str) 

Output:

Original string: Engineering
String after removal of character: Enineering


5. Removal of character from a string using translate() method

str = 'Engineer123Discipline'

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

Output:

EngineerDiscipline


References

  • Python String
  • Python removal of character from a string

How do you remove unwanted characters from text in Python?

Remove Character in Python Using translate() For this method to work, we have to specify the Unicode value for the strings, which we can get via the ord() function. For example, any_string. ranslate({ord('a'):ord('z'), ord('b'):ord('y')}) will replace occurrences of 'a' with 'z' and 'b' with 'y' .

How do you remove a character in Python?

In python, to remove Unicode ” u “ character from string then, we can use the replace() method to remove the Unicode ” u ” from the string. After writing the above code (python remove Unicode ” u ” from a string), Ones you will print “ string_unicode ” then the output will appear as a “ Python is easy. ”.

How do I remove all characters from a string in Python?

Python Remove Character from a String – How to Delete Characters from Strings. In Python you can use the replace() and translate() methods to specify which characters you want to remove from a string and return a new modified string result.

How do you remove part of a text in Python?

Remove a part of a string in Python.
Remove a substring by replacing it with an empty string. ... .
Remove leading and trailing characters: strip().
Remove leading characters: lstrip().
Remove trailing characters: rstrip().
Remove prefix: removeprefix() (Python 3.9 or later).
Remove suffix: removesuffix() (Python 3.9 or later).