因此,我有一堆长字符串,因此想出一种有效的方法来执行此操作,假设我有一个字符串,如下所示
"< stuff to remove> get this stuff <stuff to remove>所以,我正在试着提取"get this this“
所以我正在写一些类似这样的东西。
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实现这一点的更好方法是什么?
发布于 2012-04-11 01:11:26
使用正则表达式:
>>> s = "< stuff to remove> get this stuff <stuff to remove>"
>>> import re
>>> re.sub(r'<[^<>]*>', '', s)
' get this stuff '表达式<[^<>]*>匹配以<开头、以>结尾、中间没有<或>的字符串。然后,sub命令将匹配替换为空字符串,从而将其删除。
然后,如果需要,可以对结果调用.strip()来删除前导空格和尾随空格。
当然,当您有嵌套标记时,这将失败,但它将适用于您的示例。
发布于 2012-04-11 01:11:59
正则表达式是一种简单的方法(尽管不一定像jedwards的答案所示的那样更快):
import re
s = '< stuff to remove> get this stuff <stuff to remove>'
s = re.sub(r'<[^>]*>', '', s)在此s之后将是字符串' get this stuff '。
发布于 2012-04-11 01:16:55
我不确定你正在做的搜索操作是否是问题的一部分。如果你只是说你有一个开始索引和一个结束索引,并且你想从一个字符串中删除这些字符,你不需要一个特殊的函数。Python允许您对字符串中的字符使用数字索引。
> x="abcdefg"
> x[1:3]
'bc'您想要执行的操作应该类似于x[:strt_idx] + x[end_idx:]。(如果省略第一个参数,则表示“从头开始”;如果省略第二个参数,则表示“继续到结尾”。)
https://stackoverflow.com/questions/10093186
复制相似问题