Python Remove Character from String

Previous
Next

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.

str = "java2blog" str = str.replace('a','') print(str)

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.

str = "java2blog" str = str.replace('a','',1) print(str)

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

str1 = "java2blog" mid = len(str1)//2 str1 = str1[:mid] + str1[(mid+1):] print(str1)

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.

str = "java2blog" print(str.translate({ord('a'): None}))

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

str = "java2blog" print(str.translate({ord(i): None for i in 'al'}))

Output:

jv2bog

That’s all about Python Remove Character from String

Previous
Next

Add Comment