Python Remove Character from String Example
Hello in this tutorial, we will explain the different ways to remove the occurrences of a character from a string in the python programming language.
1. Introduction
To remove the occurrences of a character from a string in the python programming language we will use the two commonly used replace
and translate
methods.
- Using the string
replace()
method we can replace the search character with a new character. If we provide an empty string as the second argument to this method, then the character will get removed from the string - Using the string
translate()
method we can replace each character in the string using the given translation table
Remember as the string is immutable in the python programming language so the original string remains unchanged and a new string is returned.
1.1 Setting up Python
If someone needs to go through the Python installation on Windows, please watch this link. You can download the Python from this link.
2. Python Remove Character from String Example
I am using JetBrains PyCharm as my preferred IDE. You are free to choose the IDE of their choice.
2.1 replace() and translate() function
Let us understand this with the help of a code snippet.
replace() and translate() function
# python remove character from a string search_key = 'e' # approach1 - Using string replace() function def replace(): car_name = 'Mercedes' print('New car name = {}\n'.format(car_name.replace(search_key, ''))) # approach2 - Using string translate() function def translate(): car_name = 'Bentley' # ‘None’ as a replacement to remove it from the result string # here the ord() function is used to get the Unicode point of the character print('New car name = {}'.format(car_name.translate({ord(search_key): None}))) # replacing multiple characters using the iterator in the translate() function random_string = 'xyz12345yzx67890zyx' print(random_string.translate({ord(i): None for i in 'xyz'})) def main(): print('==== replace() function =====') replace() print('==== translate() function =====') translate() if __name__ == "__main__": main() print("\nDone")
If everything goes well the following output will be shown in the IDE console.
Console Output
==== replace() function ===== New car name = Mrcds ==== translate() function ===== New car name = Bntly 1234567890 Done
That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!
3. Summary
In this tutorial, we learned:
- An introduction to
replace()
andtranslate()
methods in the python programming language - Sample program to understand the
replace()
andtranslate()
methods
You can download the source code of this tutorial from the Downloads section.
4. Download the Project
This was an example of replace()
and translate()
methods in the python programming language.
You can download the full source code of this example here: Python Remove Character from String Example