基本信息
文件名称:Python程序从给定字符串中删除后缀.docx
文件大小:15.72 KB
总页数:3 页
更新时间:2025-05-20
总字数:约1.38千字
文档摘要

Python程序从给定字符串中删除后缀

在这个程序中,我们使用一个预定义的函数,即endswith(),将后缀字符串设置到其中,并通过表示-(减号)符号删除后缀的长度并得到结果。

str_name=RANSOMEWARE

ifstr_name.endswith(car):

str_name=str_name[:-len(WARE)]

print(Afterdeletingthegivensuffix:,str_name)

Afterdeletingthegivensuffix:RANSOME

在这个程序中,我们使用两个变量-输入字符串和后缀字符串,然后使用预定义的函数即endswith()来设置后缀字符串。为了删除后缀子字符串,我们将后缀变量的长度从给定字符串变量的总长度中减去。

str_name=Doctorate

suffix_name=ate

ifstr_name.endswith(suffix_name):

str_name=str_name[:len(str_name)-len(suffix_name)]

print(Afterdeletingthegivensuffix:,str_name)

Afterdeletingthegivensuffix:Doctor

Example3的中文翻译为:

在此程序中,我们使用预定义函数rstrip()从给定字符串中删除后缀子字符串并获取结果。

str_name=Rectangle

str_name=str_name.rstrip(gle)

print(Afterdeletingthegivensuffix:,str_name)

Afterdeletingthegivensuffix:Rectan

Example4的中文翻译为:

在下面的示例中,我们将开始将输入字符串存储在变量str_name中。然后将删除的子字符串存储在变量del_suffix中。然后使用if语句使用内置方法endswith()检查字符串删除的条件。接下来,使用接受两个参数的替换方法-del_suffix(删除子字符串)和(空字符串来存储其余字符串)。然后借助变量del_suffix打印结果。

str_name=abcdefghi

del_suffix=ghi

ifstr_name.endswith(del_suffix):

str_name=str_name.replace(del_suffix,)

print(Afterdeletethesubstringfromthegivenstring:,str_name)

Afterdeletingthesubstringfromthegivenstring:abcdef

我们探索了从给定字符串中删除后缀子字符串的概念。我们看到这个程序有3个例子,求解的方式不同,分别采用长度运算和预定义的方法。此类程序通常用于删除以相同后缀结尾的多个单词。