


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!

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

ListsandNumPyarraysinPythonhavedifferentmemoryfootprints:listsaremoreflexiblebutlessmemory-efficient,whileNumPyarraysareoptimizedfornumericaldata.1)Listsstorereferencestoobjects,withoverheadaround64byteson64-bitsystems.2)NumPyarraysstoredatacontiguou

ToensurePythonscriptsbehavecorrectlyacrossdevelopment,staging,andproduction,usethesestrategies:1)Environmentvariablesforsimplesettings,2)Configurationfilesforcomplexsetups,and3)Dynamicloadingforadaptability.Eachmethodoffersuniquebenefitsandrequiresca

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools
