Remove Characters From String In Python

The string is a type which consists of non, single or multiple characters. But in general, a string consists of multiple characters. In some cases, we may need to remove or replace some characters in a string. Python provides different ways and methods in order to remove characters.

Remove Characters with replace() Method

Python provides the replace() method for all string types like string variable and string literal. The replace() method simply replaces the given characters with newly provided characters. We can also call the replace() method an official way to replace characters in Python. The replace() method has the following syntax.

STRING.replace( OLD , NEW )
  • STRING is a string variable or strings literal.
  • OLD is the old characters which will be changed into the NEW.
  • NEW is the new characters which will replace the OLD characters.

In the following example we will change all “linux” characters with the “windows” characters.

sentence = "I like linux and use linux for a long time."

sentence = sentence.replace("linux","windows")

Remove Characters with translate() Method

Python translate() method also provides the ability to replace given characters or strings with a new one. The translation is similar to language translation. It is generally used to translate different character encoding like Unicode, ASCII, etc. The translate() method has the following syntax. Multiple replacement characters can be specified for the translate method as multiple dictionary key/value pairs.

STRING.translate({OLD:NEW,...})
  • STRING is a string variable or strings literal.
  • OLD is the old characters which will be changed into the NEW.
  • NEW is the new characters which will replace the OLD characters.

In the following example we will change all “linux” characters with the “windows” characters.

sentence = "I like linux and use linux for a long time."

sentence = sentence.translate({"linux":"windows"})

Leave a Comment