Python Remove Character from String

Filed Under: Python
Python Remove Character From String

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.


  1. Affan Ahmed says:

    s=[‘#’,’Mini Skirt’,’Skirt’,’Chiffon Top’,’T-Shirt’,’Classic’,’Classical’,’Essential’,’Short-Sleeve’,’shirt’,’Top’,’Premium’,’leggings’,’Classic’,’Pullover’,’Sweatshirt’,’Hoodie’,’Zipped’]
    finale =[]
    for i in range(0,len(TrendingApparelTexts2)):# length of your sentence string list
    processing = TrendingApparelTexts2[i] #storing each sentence to be compaired

    for j in range(0,len(s)): # iterating through the dictionary of words I don’t want in my sentences

    Delete = s[j]
    if Delete in processing:
    processing = processing.replace(Delete,”)


  2. Ranjith says:

    Receive an input text from the user and print all letters except ‘e’ and ‘s’ by using for loop?

  3. Meena Vyas says:

    # try this
    s=input(“Enter a string:\n”)
    delete=input(“enter string to delete\n”)




    1. Sai Prasad says:


  4. ... says:

    How would I delete all characters bar the first character, without specifying the character:
    For example, I have a bunch of items:
    passion fruit
    Say I wanted the user to guess the word only given the first letter of each word (each WORD not each item, eg for passion fruit, the user is given ‘p f ‘ not just ‘p ‘, how would I do that?

    1. sunil says:

      #try this

      def guessgame(s):
      for i in range(1,len(s)):
      if s[i-1]==’ ‘:
      return l

      l=guessgame(“passion fruit”)

      1. Pãvãñ says:

        How to learn python

    2. Gokul Jayan says:

      for i in l:

  5. zara says:

    Hi Pankaj. I have a problem in removing character from string. Actually, I don’t know why the following program is unable to remove character from second string. could you please help me?
    # Type your code here
    def anagrams(my_string1, my_string2):
    if len(my_string1)!=len(my_string2):
    out_put= False
    for i in a:
    if i in b:
    out_put = True
    return out_put

    1. sunil says:

      your program’s objective is removing the same characters from string and value of out_put depends on the last character ,if it is same in both string it will return true otherwise return False.
      it is removing same characters from both string. It is working good for above mentioned objective.

  6. Daniel H O'Hearn says:

    How can I remove I greater number of items?

    For example, if I wanted to remove 1000 characters you don’t necessarily want to type out and replace with some other string.

  7. sundara rajan says:

    How to remove backslash from a string?

    1. Muhammad Roshan ali says:

      use r like raw strings i guess

  8. lallan says:

    I need to make a program that takes a sentence and outputs it without spaces. Can you help me?

    1. Jzjzj says:

      D=input(“write sentence:”)
      print(d.replace(” “, “”)

  9. A S says:

    import pickle

    code1 = (“1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010”)
    l = list(code1)

    pickle.dump(code1, open(“code1”, “wb”))
    print(“original list”)

    Stuck here, how can i add/remove more numbers to this code?

  10. boopathi says:

    fs=fs.replace( …….);

  11. ibrahim says:

    HI @Pankaj i want to replace or remove some variable from string that should not be print in after execution it should remove couple multi variable not only one variable so how can i do that
    Ex:– from a input string we need to remove set of variable and need to print after removing it.
    so how can i do it i have tried with replace and TRAN but its not working.
    so help me out.

    1. sunil says:

      #try this

      s=input(“mainstring : “)
      l=input(“characters’s you want to remove : “)
      for i in s:
      if i not in l:

  12. Ash says:


    I have list of tuple. From that I want to remove few characters from tuple. Please check the below example:

    x = [(‘url/user/123’, ‘url/site/2’), (‘url/user/125’, ‘url/site/5’)]

    expected result: [(‘123’, ‘2’), [(‘125’, ‘5’)]]

    1. Pankaj says:

      You will have to write custom code for this. For each string, check every character and pick only digits.

  13. vrushali ingulkar says:

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

  14. 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

      1. Apple says:

        Without any function except print()

      2. Mikhayiyl says:

        How about removing the i at index 5 to get “inital” output

  15. 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-

    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


    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]

    2. Aditya says:

      Here is the solution df[‘column’]=df[‘column’].str.replace(‘km/kg’ , ‘ ‘)

  16. Dmitriy says:

    Nice article.Thanks!

  17. 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:]

      that should work

      1. Johnny says:

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

      2. Sabtain Raza says:


  18. 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.

  19. 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.

      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!

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors