搜索
首页后端开发Python教程使用Python从字符串的末尾删除给定的子字符串

使用Python从字符串的末尾删除给定的子字符串

Python 是一种全球使用的编程语言,开发人员出于不同的目的使用它。 Python 具有各种不同的应用程序,例如 Web 开发、数据科学、机器学习,还可以自动化执行不同的流程。所有使用 python 的不同程序员都必须处理字符串和子字符串。因此,在本文中,我们将学习如何删除字符串末尾的子字符串。

删除子字符串的不同方法

使用函数

我们将使用endswith()函数来帮助我们删除字符串末尾的子字符串。为了更清楚地理解它,我们将举以下例子:

示例

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)

输出

上述代码的输出如下:

Hello Everyone, I am John

分割字符串

在此方法中,我们将对字符串末尾的子字符串进行切片。 Python 提供了对代码中存在的文本或字符串进行切片的功能。我们将在程序中定义子字符串,并相应地对其进行切片。使用此方法删除子字符串的代码和示例如下:

示例

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)

输出

上述代码的输出如下:

Hello Everyone, I am John

重新模块

Python 编程语言中存在的 re 模块用于处理常规函数。我们可以使用 re 模块的一个这样的函数来删除字符串末尾的子字符串。我们将使用的函数是 re.sub() 函数。使用re模块函数删除字符串最后一个子字符串的代码和示例如下:

示例

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)

输出

上述代码的输出如下:

Hello Everyone, I am John

与函数一起切片

在这种情况下将使用 rfind() 函数,它从右侧开始查找定义的子字符串,然后我们可以借助切片功能删除子字符串。您可以借助以下示例更好地理解它:

示例

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)

输出

上述代码的输出如下:

Hello Everyone, I am John

使用捕获组重新模块

这是使用 re 模块删除字符串末尾存在的子字符串的另一种方法。捕获组与正则表达式模块一起使用来删除子字符串。借助捕获组删除子字符串的代码和示例如下:

示例

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)

输出

上述代码的输出如下:

Hello Everyone, I am John

结论

在全球范围内的所有用户中,更改字符串的需求是很常见的,但如果不遵循正确的方法,删除字符串的过程很多时候会消耗大量时间。因此,本文描述了上面提到的许多不同的方法,这些方法可用于使用 python 从字符串末尾删除子字符串。可能还有其他方法可以删除子字符串,但本文提到的方法是建议的最短和最简单的方法,您可以根据您的应用领域进行选择。

以上是使用Python从字符串的末尾删除给定的子字符串的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:tutorialspoint。如有侵权,请联系admin@php.cn删除
列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

说明如何将内存分配给Python中的列表与数组。说明如何将内存分配给Python中的列表与数组。May 03, 2025 am 12:10 AM

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

您如何在Python数组中指定元素的数据类型?您如何在Python数组中指定元素的数据类型?May 03, 2025 am 12:06 AM

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

什么是Numpy,为什么对于Python中的数值计算很重要?什么是Numpy,为什么对于Python中的数值计算很重要?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

讨论'连续内存分配”的概念及其对数组的重要性。讨论'连续内存分配”的概念及其对数组的重要性。May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

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

在Numpy阵列上可以执行哪些常见操作?在Numpy阵列上可以执行哪些常见操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,减法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的数据分析中如何使用阵列?Python的数据分析中如何使用阵列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具