Tutorial

How To Remove Characters from a String in Python

Updated on June 18, 2024
authorauthor

Pankaj and Andrea Anderson

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.

Deploy your Python applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on scaling your app.

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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author


Default avatar

Technical Editor


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
October 16, 2018

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?

- MIllena

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    February 6, 2019

    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.

    - Joy

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      April 2, 2019

      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”

      - Prakash choudhary

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        April 3, 2019

        Nice article.Thanks!

        - Dmitriy

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          August 7, 2019

          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

          - AJAY

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            September 7, 2019

            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

            - Shankar

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              September 14, 2019

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

              - vrushali ingulkar

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                January 11, 2020

                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’)]]

                - Ash

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  March 26, 2020

                  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.

                  - ibrahim

                    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 below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Become a contributor for community

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      DigitalOcean Documentation

                      Full documentation for every DigitalOcean product.

                      Resources for startups and SMBs

                      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                      Get our newsletter

                      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                      New accounts only. By submitting your email you agree to our Privacy Policy

                      The developer cloud

                      Scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Get started for free

                      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                      *This promotional offer applies to new accounts only.