我试图从字符串末尾删除特定的单词,直到字符串末尾不再有这些单词为止。你知道吗
我尝试了以下方法:
companylist=['dell inc corp', 'the co dell corp inc', 'the co dell corp inc co']
def rchop(thestring, ending):
if thestring.endswith(ending):
return thestring[:-len(ending)]
return thestring
for item in companylist:
item = rchop(item,' co')
item = rchop(item,' corp')
item = rchop(item,' inc')
我期待以下结果:
dell
the co dell
the co dell
但我得到的结果是:
dell
the co dell corp
the co dell corp
如何使结果不依赖于替换词的顺序,以便我的结果表示从字符串末尾开始的所有替换词的穷尽?你知道吗
您应该使用:
或者感谢@RoadRunner:
现在两种情况都出现了:
是:
使用正则表达式。你知道吗
例如:
输出:
如果最后一个单词在其他单词列表中,可以使用此选项删除它:
输出:
如果您只想删除最后一个单词,无论它是什么,您都可以使用:
输出:
string[:i]
部分是第i空间之前的所有内容,string[i:]
部分是第i空间之后的所有内容。你知道吗相关问题 更多 >
编程相关推荐