


Remove a given substring from the end of a string using Python
Python is a programming language used globally and developers use it for different purposes. Python has a variety of different applications such as web development, data science, machine learning, and can also automate different processes. All the different programmers using python have to deal with strings and substrings. So, in this article, we will learn how to remove substring at the end of a string.
Different ways to delete substrings
Use functions
We will use the endswith() function to help us remove the substring at the end of the string. To understand it more clearly, we will give the following example:
Example
def remove_substring(string, substring): #Defining two different parameters if string.endswith(substring): return string[:len(string)-len(substring)] #If substring is present at the end of the string then the length of the substring is removed from the string else: return string #If there is no substring at the end, it will return with the same length # Example text = "Hello Everyone, I am John, The Sailor!" last_substring = ", The Sailor!" #Specifying the substring #Do not forget to enter the last exclamation mark, not entering the punctuations might lead to error Without_substring = remove_substring(text, last_substring) print(Without_substring)
Output
The output of the above code is as follows:
Hello Everyone, I am John
Split string
In this method, we will slice the substring at the end of the string. Python provides functionality to slice text or strings present in the code. We will define the substring in the program and slice it accordingly. Code and examples for removing substrings using this method are as follows:
Example
def remove_substring(string, substring): if string[-len(substring):] == substring: #The length of last characters of the string (length of substring) is compared with the substring and if they are same the substring is removed return string[:-len(substring)] else: return string #If the length of last characters(Substring) does not match with the length of last substring then the characters are not removed # Example Whole_string = "Hello Everyone, I am John, the Sailor!" last_substring = ", the Sailor!" Final_String = remove_substring(Whole_string, last_substring) print(Final_String)
Output
The output of the above code is as follows:
Hello Everyone, I am John
Re-module
The re module exists in the Python programming language to handle regular functions. We can use one such function from the re module to remove the substring at the end of the string. The function we will use is the re.sub() function. The code and example of using the re module function to delete the last substring of a string are as follows:Example
import re #Do not forget to import re module or it might lead to error while running the program def remove_substring(string, substring): pattern = re.escape(substring) + r'$' #re.escape is used to create a pattern to treat all symbols equally and it includes $ to work only on the substring on the end of the string return re.sub(pattern, '', string) #This replaces the last substring with an empty space # Example Whole_string = "Hello Everyone, I am John, the Sailor!" last_substring = ", the Sailor!" Final_String = remove_substring(Whole_string, last_substring) print(Final_String)
Output
The output of the above code is as follows:
Hello Everyone, I am John
Slicing with functions
In this case rfind() function will be used which finds the defined substring starting from the right side and then we can remove the substring with the help of slicing function. You can understand it better with the help of following examples:
Example
def remove_substring(string, substring): index = string.rfind(substring) #rfind() is used to find the highest index of the substring in the string if index != -1 and index + len(substring) == len(string): # If a substring is found, it is removed by slicing the string return string[:index] else: return string #If no substring is found the original string is returned # Example Whole_string = "Hello Everyone, I am John, the Sailor!" last_substring = ", the Sailor!" Final_String = remove_substring(Whole_string, last_substring) print(Final_String)
Output
The output of the above code is as follows:
Hello Everyone, I am John
Re-module using capture group
This is another way to remove substrings present at the end of a string using the re module. Capturing groups are used with the regular expression module to remove substrings. The code and examples for deleting substrings with the help of capturing groups are as follows:
Example
import re #Do not forget to import the re module or error might occur while running the code def remove_substring(string, substring): pattern = re.escape(substring) + r'(?=$)' # A function is created first and re.escape is used so that all the functions are created equally return re.sub(pattern, '', string) # With the help of re.sub() function, the substring will be replaced with empty place # Example Whole_string = "Hello Everyone, I am John, the Sailor!" last_substring = ", the Sailor!" Final_String = remove_substring(Whole_string, last_substring) print(Final_String)
Output
The output of the above code is as follows:
Hello Everyone, I am John
in conclusion
The need to change strings is very common among all users across the globe, but the process of deleting strings many times consumes a lot of time if the correct method is not followed. Therefore, this article describes the many different methods mentioned above that can be used to remove a substring from the end of a string using python. There may be other ways to remove substrings, but the method mentioned in this article is the shortest and simplest suggested method and you can choose according to your application domain.
The above is the detailed content of Remove a given substring from the end of a string using Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

Using python in Linux terminal...

Fastapi ...

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...
