Remove Multiple Characters from a String in PythonWe already know that strings are defined as a sequence of characters, and we can perform a variety of operations on them. In this tutorial, we will learn one more interesting task that can be accomplished using strings in Python. Here we will see how we can remove multiple characters from it. We have listed below the methods that we will learn to meet our objective.
Using nested replace()In the program given below, we will see how replace() is used to remove multiple characters from the string. Output: The initialized string is learnpythonlearn The string after replacing the characters is eearnpythoneearn Explanation-
In the second program, we will see how translate() and maketrans() can be used to do the same. The users must keep this thing in their mind that it only works in Python 2. Using translate() and maketrans()The following program shows how it can be done. Output: The initialized string is learnpythonlearn The string after replacing the characters is eearnpythoneearn Explanation-
Now we will discuss how re.subn() can become an aid for this. The subn() returns a new string with the total number of replacements. Using re.subn()The program given below shows how it can be done. Output: To get the result AAA, we can multiply AA by AA Explanation-
In the last program, we will do the same thing using sub() Using re.sub()The following program illustrates how it can be done- Output: To get the result ZZZ, we can multiply ZZ by ZZ Explanation-
ConclusionIn this tutorial, we learned how we can remove multiple characters from a string using Python.
Next TopicShuffle in Python
|
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week