Skip to main content
 首页 » 编程设计

python之根据开始索引和结束索引删除字符串

2025年05月04日28yjmyzz

所以,我有一堆长字符串,因此想到了一种执行此操作的有效方法 假设我有一个类似的字符串

 "< stuff to remove> get this stuff <stuff to remove> 

所以,我正在尝试提取“get this stuff”

所以我正在写这样的东西。

 strt_pos = 0 
  end_pos = 0 
 while True: 
   strt_idx = string.find(start_point, strt_pos) # start_point = "<" in our example 
   end_idx  = string.find(end_point, end_pos)   # end_point = ">" in our example 
   chunk_to_remove = string[strt_idx:end_idx] 
    # Now how do i chop this part off from the string?? 
   strt_pos = strt_pos + 1 
    end_pos = end_pos + 1 
   if str_pos >= len(string) # or maybe end_pos >= len(string): 
      break 

什么是更好的实现方式

请您参考如下方法:

使用正则表达式:

>>> s = "< stuff to remove> get this stuff <stuff to remove>" 
>>> import re 
>>> re.sub(r'<[^<>]*>', '', s) 
' get this stuff ' 

表达式<[^<>]*>匹配以 < 开头的字符串, 以 > 结尾, 并且都没有 <或 >之间。 sub然后命令用空字符串替换匹配项,从而将其删除。

然后您可以调用 .strip()如果需要,可以在结果上删除前导和尾随空格。

当然,当你有嵌套标签时,这会失败,但它适用于你的例子。