从字符串末尾删除特定单词

2024-06-16 11:08:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从字符串末尾删除特定的单词,直到字符串末尾不再有这些单词为止。你知道吗

我尝试了以下方法:

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

如何使结果不依赖于替换词的顺序,以便我的结果表示从字符串末尾开始的所有替换词的穷尽?你知道吗


Tags: the方法字符串returnendingitem单词dell
3条回答

您应该使用:

companylist = ['dell inc corp', 'co dell corp inc', 'co dell corp inc co']
for idx, item in enumerate(companylist):
    companylist[idx] = item.replace(' co', '')
    companylist[idx] = item.replace(' corp', '')
    companylist[idx] = item.replace(' inc', '')

或者感谢@RoadRunner:

companylist = [item.replace(' co', '').replace(' corp', '').replace(' inc', '') for item in companylist]

现在两种情况都出现了:

print(companylist)

是:

['dell', 'co dell', 'co dell']

使用正则表达式。你知道吗

例如:

import re

companylist=['dell inc corp', 'co dell corp inc', 'co dell corp inc co']
for i in companylist:
    print(re.sub(r"\W(corp|inc|co)\b", "", i))

输出:

dell
co dell
co dell

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

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空间之后的所有内容。你知道吗

相关问题 更多 >