【发布时间】:2011-12-29 07:07:58
【问题描述】:
我有一个长字符串和一个[end-index, string] 列表,如下所示:
long_sentence = "This is a long long long long sentence"
indices = [[6, "is"], [8, "is a"], [18, "long"], [23, "long"]]
元素6, "is" 表示6 是字符串中单词"is" 的结束索引。我想最后得到以下字符串:
>> print long_sentence
This .... long ......... long sentence"
我试过这样的方法:
temp = long_sentence
for i in indices:
temp = temp[:int(i[0]) - len(i[1])] + '.'*(len(i[1])+1) + temp[i[0]+1:]
虽然这似乎有效,但它需要的时间非常长(300 MB 文件中的 5000 个字符串超过 6 小时)。有没有办法加快速度?
【问题讨论】:
-
旁注:您不需要
int()部分,因为i[0]是一个整数。