Python Remove Character from String

Filed Under: Python

Sometimes we want to remove all occurrences of a character from a string. There are two common ways to achieve this.

Python Remove Character from String

  1. Using string replace() function
  2. Using string translate() function

Python Remove Character from String using replace()

We can use string replace() function to replace a character with a new character. If we provide an empty string as the second argument, then the character will get removed from the string.

Note that the string is immutable in Python, so this function will return a new string and the original string will remain unchanged.


s = 'abc12321cba'

print(s.replace('a', ''))

Output: bc12321cb

Python Remove Character from String using translate()

Python string translate() function replace each character in the string using the given translation table. We have to specify the Unicode code point for the character and ‘None’ as a replacement to remove it from the result string. We can use ord() function to get the Unicode code point of a character.


s = 'abc12321cba'

print(s.translate({ord('a'): None}))

Output: bc12321cb

If you want to replace multiple characters, that can be done easily using an iterator. Let’s see how to remove characters ‘a’, ‘b’ and ‘c’ from a string.


s = 'abc12321cba'

print(s.translate({ord(i): None for i in 'abc'}))

Output: 12321

Removing Spaces from a String


s = ' 1 2 3 4 '
print(s.replace(' ', ''))  # 1234
print(s.translate({ord(i): None for i in ' '}))  # 1234

Python Remove newline from String


s = 'ab\ncd\nef'
print(s.replace('\n', ''))
print(s.translate({ord('\n'): None}))

Remove substring from string

String replace() function arguments is string. Let’s see how to remove a word from a string.


s = 'ab12abc34ba'
print(s.replace('ab', ''))

Output: 12c34ba

Remove specified number of times

We can also pass a third parameter in replace() function to specify the number of times replacement should be performed.


s = 'abababab'
print(s.replace('a', 'A', 2))

Output: AbAbabab

You can checkout complete python script and more Python examples from our GitHub Repository.

Comments

  1. vrushali ingulkar says:

    i want to replace lowercase characters before and after key in given string “there is A key to Success”

  2. Shankar says:

    Sir ,it removes all the character.
    For eg:
    If I remove ‘i’ in ‘initial’.
    It’s output is ‘ntal’.(it removes all ‘i’ in the string

    1. Aamir says:

      s = “initial”
      print(s.replace(‘i’, ”, 1))
      use it

  3. AJAY says:

    Pankaj , your article was nice, but i stuck in solving same kind of problem. Can you help me.

    I have a dataset and i want to remove certain character from column. Column datatype is object. I am giving you example below-

    Mileage
    21.6 km/kg
    18.2 kmpl
    and so on,
    I have number of values. I want to remove km/kg and kmpl from the columns values. How can i do that.

    Thanks & Regards

    Ajay

    1. Sabtain raza says:

      you can do this simply split string on the base of space
      example code is here
      str1=”21.6 km/kg”
      res=str1.split(” “)[0]

  4. Dmitriy says:

    Nice article.Thanks!

  5. Prakash choudhary says:

    i want to remove only first char from a string but in this its remove all char related to that……
    for an example “helloworld” this is string i want remove only first “h” from string “helloworld”

    1. Johnny says:

      newString = list(‘string’)[1:]
      newString.join(x)

      that should work

      1. Johnny says:

        second line should actually be ”.join(newString)
        my bad

      2. Sabtain Raza says:

        newString=string[1:]

  6. Joy says:

    Can you please add the third argument replace() can take, which is the number of times the character will be replaced if there are multiple instances of the character within the string? I’m a beginner in python and I was trying to remove a character from a string but only a certain amount of times, not all instances. When I searched google, your article was the top result. But I had to browse several stack overflow threads to get the information. If you add it to your article, you might just make it easy for the next beginner in python.

    1. Pankaj says:

      I have added an example for replacement of a specific number of counts. However, if you would have looked into the replace() function documentation, it clearly states that we can pass ‘count’ variable to specify the maximum number of occurrences to replace.

  7. MIllena says:

    Why do you copy standard library’s doc? What’s the point? You won’t teach anybody that way. One can read the documentation 10 times, learn everything about oop, functions, types, loops, etc and won’t be able to write two useful lines of code. Do you know why?

    1. Pankaj says:

      Can you show me where in Python documentation, two methods are provided to remove character or substring from a String? Just look at the translate() function Python documentation, there is not a single example.

      https://docs.python.org/3.7/library/stdtypes.html#str.translate

      You also mentioned copying standard docs, can you point me what part of the post is copied?

      I have written this post from my experience of working with Python for many years. If my post helps even one person, I will be happy.

      1. Alex says:

        Pankaj, your article was very helpful for me, thank you! Keep up the good work!

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages