// Tutorial //

How To Remove Characters from a String in Python

Published on August 3, 2022 · Updated on December 12, 2022
Default avatar
By Pankaj
Developer and author at DigitalOcean.
How To Remove Characters from a String in Python

Introduction

This article describes two common methods that you can use to remove characters from a string using Python:

  • the String replace() method
  • the String translate() method

To learn some different ways to remove spaces from a string in Python, refer to Remove Spaces from a String in Python.

A Python String object is immutable, so you can’t change its value. Any method that manipulates a string value returns a new String object.

The examples in this tutorial use the Python interactive console in the command line to demonstrate different methods that remove characters.

Remove Characters From a String Using the replace() Method

The String replace() method replaces a character with a new character. You can remove a character from a string by providing the character(s) to replace as the first argument and an empty string as the second argument.

Declare the string variable:

  1. s = 'abc12321cba'

Replace the character with an empty string:

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

The output is:

Output
bc12321cb

The output shows that both occurrences of the character a were removed from the string.

Remove Newline Characters From a String Using the replace() Method

Declare a string variable with some newline characters:

  1. s = 'ab\ncd\nef'

Replace the newline character with an empty string:

  1. print(s.replace('\n', ''))

The output is:

Output
abcdef

The output shows that both newline characters (\n) were removed from the string.

Remove a Substring from a String Using the replace() Method

The replace() method takes strings as arguments, so you can also replace a word in string.

Declare the string variable:

  1. s = 'Helloabc'

Replace a word with an empty string:

  1. print(s.replace('Hello', ''))

The output is:

Output
abc

The output shows that the string Hello was removed from the input string.

Remove Characters a Specific Number of Times Using the replace() Method

You can pass a third argument in the replace() method to specify the number of replacements to perform in the string before stopping. For example, if you specify 2 as the third argument, then only the first 2 occurrences of the given characters are replaced.

Declare the string variable:

  1. s = 'abababab'

Replace the first two occurrences of the character with the new character:

  1. print(s.replace('a', 'A', 2)) # perform replacement twice

The output is:

Output
AbAbabab

The output shows that the first two occurrences of the a character were replaced by the A character. Since the replacement was done only twice, the other occurrences of a remain in the string.

Remove Characters From a String Using the translate() Method

The Python string translate() method replaces each character in the string using the given mapping table or dictionary.

Declare a string variable:

  1. s = 'abc12321cba'

Get the Unicode code point value of a character and replace it with None:

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

The output is:

Output
ac12321ca

The output shows that both occurrences of the b character were removed from the string as defined in the custom dictionary.

Remove Multiple Characters From a String using the translate() method

You can replace multiple characters in a string using the translate() method. The following example uses a custom dictionary, {ord(i): None for i in 'abc'}, that replaces all occurrences of a, b, and c in the given string with None.

Declare the string variable:

  1. s = 'abc12321cba'

Replace all the characters abc with None:

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

The output is:

Output
12321

The output shows that all occurrences of a, b, and c were removed from the string as defined in the custom dictionary.

Remove Newline Characters From a String Using the translate() Method

You can replace newline characters in a string using the translate() method. The following example uses a custom dictionary, {ord('\n'): None}, that replaces all occurrences of \n in the given string with None.

Declare the string variable:

  1. s = 'ab\ncd\nef'

Replace all the \n characters with None:

  1. print(s.translate({ord('\n'): None}))

The output is:

Output
abcdef

The output shows that all occurrences of the newline character \n were removed from the string as defined in the custom dictionary.

Conclusion

In this tutorial, you learned some of the methods you can use to remove characters from strings in Python. Continue your learning about Python strings.

Want to deploy your application quickly? Try Cloudways, the #1 managed hosting provider for small-to-medium businesses, agencies, and developers - for free. DigitalOcean and Cloudways together will give you a reliable, scalable, and hassle-free managed hosting experience with anytime support that makes all your hosting worries a thing of the past. Start with $100 in free credits!

Learn more here


About the authors
Default avatar
Pankaj

author

Developer and author at DigitalOcean.

Default avatar
Technical Editor

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
January 22, 2022

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

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    November 3, 2021

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

    - Ranjith

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      May 18, 2021

      # 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

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        December 10, 2020

        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?

        - …

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          November 23, 2020

          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

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            September 25, 2020

            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

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              July 18, 2020

              How to remove backslash from a string?

              - sundara rajan

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                June 28, 2020

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

                - lallan

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  June 9, 2020

                  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

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    May 12, 2020

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

                    - boopathi

                      Try DigitalOcean for free

                      Click here to Sign up and get $200 of credit to try our products over 60 days!