How to Remove Substring from a String in Python
Table of Contents
In Python, a string can be thought of as a list of individual characters.
This means that we can easily remove a substring from a string.
In this post, we'll look at how you can remove a substring from a string in Python.
Using str.replace()
The most straightforward way to remove a substring from a string is to use the str.replace()
method.
This method is called on the string that you want to remove the substring from, and takes two arguments:
- The substring you want to remove
- The string you want to replace the substring with
Let's first define the string we want to work on:
PYTHONstring = "hello world"
print(string)
BASHhello world
Now, let's remove the substring "world" from the string:
PYTHONstring = "hello world"
string = string.replace("world", "")
print(string)
BASHhello
The str.replace()
method returns a new string with the substring removed, so we can just assign the result to the same variable.
Keep in mind that strings in Python are immutable, so once you create a string, you can't change it.
Conclusion
In this post, we looked at how you can remove a substring from a string in Python.
Simply use the str.replace()
method to remove a substring from a string by replacing it with an empty string.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Create an RSS Reader in Node
- Getting Started with Electron
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- How to deploy an Express app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Creating a Twitter bot with Node.js
- Setting Up Stylus CSS Preprocessor