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.

Comments

  1. 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):
    a=my_string1.lower()
    b=my_string2.lower()
    out_put=True
    if len(my_string1)!=len(my_string2):
    out_put= False
    else:
    for i in a:
    if i in b:
    a=a.strip(i)
    b=b.strip(i)
    out_put = True
    else:
    out_put=False
    return out_put
    print(anagrams(“Orchestaa”,”Carthorse”))

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

  3. sundara rajan says:

    How to remove backslash from a string?

  4. 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(” “, “”)

  5. 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”)
    print(code1)

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

  6. boopathi says:

    s=input();
    n=int(input());
    fs=fs.replace( …….);
    print(fs)

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

  8. Ash says:

    Hi,

    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.

  9. vrushali ingulkar says:

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

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

  11. 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]

  12. Dmitriy says:

    Nice article.Thanks!

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

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

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