The string is a type that 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 that will replace the OLD characters.
In the following example, we remove a single character from the string.
sentence = "I like linux and use linux for a long time."
sentence = sentence.replace(".","!")
In the following example, we will change all “linux” characters with the “windows” characters. We remove multiple characters which are “linux” and the new characters “windows”.
sentence = "I like linux and use linux for a long time."
sentence = sentence.replace("linux","windows")
Remove Characters with translate() Method
The 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 that will replace the OLD characters.
In the following example, we remove a single character from the string.
sentence = "I like linux and use linux for a long time."
sentence = sentence.translate(".","!")
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"})
Replace Last Character
The replace() and translate() methods can be used to remove the last character specifically. As a string is a list of characters the last character is indexed as -1
. By specifying the last character to these replace() or translate() methods it can be easily removed.
sentence = "I like linux and use linux for a long time."
sentence1 = sentence.replace(sentence[-1],"!")
sentence2 = sentence.translate({sentence[-1]:"!"})