In this post, we will see how to remove character from String in Python.
There are multiple ways to do it.We will see three of them over here.
Using String’s replace method
You can use Python String’s remove method to remove character from String.
Please note that String is immutable in python, so you need to assign it to new variable.
1 2 3 4 5 |
str = "java2blog" str = str.replace('a','') print(str) |
Output:
Remove only few instances of character
If you want to remove only limited number of instances of character, you need to past it as third parameter.
1 2 3 4 5 |
str = "java2blog" str = str.replace('a','',1) print(str) |
Output:
For example, over here we have just changed 1st instance of character ‘a’ to ”.
Remove character by index
If you need to remove any character by index, you can use below formula
Let’s say we want to remove middle character from String "java2blog"
you can do it as follow
1 2 3 4 5 6 |
str1 = "java2blog" mid = len(str1)//2 str1 = str1[:mid] + str1[(mid+1):] print(str1) |
Output:
Using translate method
You can use String’s translate method as well to remove character from String.You need to pass unicode of the character and None to replace character with nothing.
1 2 3 4 |
str = "java2blog" print(str.translate({ord('a'): None})) |
Output:
We have used Python ord function to find unicode of character.
In case you want to replace multiple characters, you can do it as follows
1 2 3 4 |
str = "java2blog" print(str.translate({ord(i): None for i in 'al'})) |
Output:
That’s all about Python Remove Character from String