Python Remove Character from String

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.

Output:

jv2blog

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.

Output:

jva2blog

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

str = str[:pos] + str[(pos+1):]

Let’s say we want to remove middle character from String "java2blog"
you can do it as follow

Output:

javablog

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.

Output:

jv2blog

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

Output:

jv2bog

That’s all about Python Remove Character from String

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *