首页 > 解决方案 > 从字符串末尾删除特定单词

问题描述

我正在尝试从字符串末尾删除特定单词,直到字符串末尾不再有这些单词。

我尝试了以下方法:

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

如何使结果不依赖于替换词的顺序,以便我的结果代表字符串末尾所有替换词的耗尽?

标签: pythonstringreplace

解决方案


如果它在其他单词列表中,您可以使用它来删除最后一个单词:

import re

string = "hello how are you"
words_to_remove = ["are", "you"]

space_positions = [x.start() for x in re.finditer('\ ', string)]
print(space_positions)
for i in reversed(space_positions):
    if string[i+1:] in words_to_remove:
        string = string[:i]

print(string)

哪个输出:

[5, 9, 13]
hello how

如果您只对删除最后一个单词感兴趣,无论它是什么,您都可以使用:

import re

string = "hello how are you?"

space_positions = [x.start() for x in re.finditer('\ ', string)]
print(space_positions)
for i in reversed(space_positions):
    print(string[:i], '---', string[i:])

哪个输出:

[5, 9, 13]
hello how are ---  you?
hello how ---  are you?
hello ---  how are you?

string[:i]部分是第 i 个空格之前的所有内容,而该string[i:]部分是第 i 个空格之后的所有内容。


推荐阅读