// Tutorial //

Python Remove Character from String

Published on August 3, 2022
Default avatar
By Pankaj
Developer and author at DigitalOcean.
Python Remove Character from String

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up
About the authors
Default avatar


Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?

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,‘’) finale.append(processing) print(finale)

- Affan Ahmed

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

    - Ranjith

      # try this s=input(“Enter a string:\n”) delete=input(“enter string to delete\n”) position=s.find(delete) length_s=len(s) length_word=len(delete) s1=s[:position] s2=s[position+length_word+1::] s3=s1+s2 print(s3)

      - Meena Vyas

        How would I delete all characters bar the first character, without specifying the character: For example, I have a bunch of items: banana apple orange mango passion fruit guava 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?

        - …

          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”))

          - zara

            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.

            - Daniel H O’Hearn

              How to remove backslash from a string?

              - sundara rajan

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

                - lallan

                  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

                  - A S

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

                    - boopathi