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
如何使结果不依赖于替换词的顺序,以便我的结果代表字符串末尾所有替换词的耗尽?
解决方案
如果它在其他单词列表中,您可以使用它来删除最后一个单词:
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 个空格之后的所有内容。
推荐阅读
- c++ - 20,000 大小字符串的 C++ 堆栈溢出
- azure - 自动从 Blob 存储中提取上传的文本文件并将数据导入 Azure SQL
- python - 在 Python 中安装 pyPDF2 时如何解决此错误
- php - 保护 Symfony VarDumper 的受保护和/或私有值
- c - 图的邻接列表表示不打印相邻节点。为什么?
- java - 如何解决错误异常 java.lang.NoSuchMethodError : 'java.lang.String javax.swing.JOptionPane.showInputDialog(java.lang.String)'
- c - CS50 凯撒 我该怎么做?
- r - Hashtag 出现在 R Markdown html 中
- python - 有没有办法在熊猫数据集中用 int 表示 str ?
- lua - 如何在 lua 中访问 .txt 文件并进行读写