How To Remove Characters from a String in Python | DigitalOcean (2024)

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.

How To Remove Characters from a String in Python | DigitalOcean (2024)
Top Articles
Multi Asset Allocation Fund: Invest in Best/Top Funds 2024
Sleeping Mat R Values Explained | Alpkit
3Movierulz
Wilson Tattoo Shops
Kaiser Ncti
Costco Gas Prices Las Vegas Nv
Halloween showing of Hocus Pocus on Thirsks Outdoor cinema, Station Road,Thirsk,YO7 1QL,GB, Northallerton, 11 October 2024
Osu Hematology
What Happened To Athena Palomino
Frontline Iep Direct Login
Craigslist Oklahoma City Oklahoma
YouTube Sperren mit Proxy umgehen - So geht's 2024 – PrivacyTutor
Choose the antonym of the given word- Rarely a) Hardly b) Frequentlyc) Definitelyd) Absolutely
Albertsons Weekly Ad Missoula
Fox 31 News Denver Co
Craigslist Cars For Sale By Owner Memphis Tn
Blood Dk Primordial Stones
Umn Pay Calendar
❤️ Red Heart Emoji Guide For All Girls and Boys
Tcc Virginia Beach Testing Center
The Express from Lock Haven, Pennsylvania
Yale College Confidential 2027
Bad And Boujee One Mo Chance Age
Culver's Flavor Of The Day Ann Arbor
Directions To Closest Cvs
Sunset On June 21 2023
Manhungay
Eli Manning Pfr
Insidekp.kp.org Myhr Portal
Imvu Hov
The Exorcist: Believer Showtimes Near Regal Jack London
Ron Martin Realty Cam
Synonym For Saint Word Craze
Dr Madhuri Gudipati
Oxford Health Plans Provider Portal
These Bathroom Cabinet Ideas Make Storage Look Beautiful
Telegram Scat
East Primesuite Login Com Citrix
Wyze Recover Deleted Events
Yh50 Pill
How To Add Friends On Regal App
Saberhealth Time Track
Pensacola Tattoo Studio 2 Reviews
Craigslist Alma Michigan
Moviehax · Watch Online Movies & Tv Show Download, Watch free movies & Tv Series. free hindi dubbed movies, latest hollywood and bollywood movies free download, watch online movies, Latest Bollywood Movies | Hindi Dubbed | Netflix Movies
My Name Is Glenn Quagmire Lyrics
Craigslist Apartments In Philly
Safe Pet Adoption Tips For Craigslist | The VetHaven
Cbx Promo Codes 2023
Cleveland Metropark Intergrove Lodge
9 Best Things To Do In Charming Surprise, Arizona
Latest Posts
Article information

Author: Stevie Stamm

Last Updated:

Views: 5484

Rating: 5 / 5 (80 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Stevie Stamm

Birthday: 1996-06-22

Address: Apt. 419 4200 Sipes Estate, East Delmerview, WY 05617

Phone: +342332224300

Job: Future Advertising Analyst

Hobby: Leather crafting, Puzzles, Leather crafting, scrapbook, Urban exploration, Cabaret, Skateboarding

Introduction: My name is Stevie Stamm, I am a colorful, sparkling, splendid, vast, open, hilarious, tender person who loves writing and wants to share my knowledge and understanding with you.