按索引列表拆分字符串 [英] Splitting a string by list of indices
本文介绍了按索引列表拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过索引列表拆分字符串,其中拆分段以一个索引开始并在下一个索引之前结束.
I want to split a string by a list of indices, where the split segments begin with one index and end before the next one.
示例:
s = 'long string that I want to split up'
indices = [0,5,12,17]
parts = [s[index:] for index in indices]
for part in parts:
print part
这将返回:
我想拆分的长字符串
我想拆分的字符串
我想分手
我想分手
long string that I want to split up
string that I want to split up
that I want to split up
I want to split up
我正在尝试:
长
字符串
那个
我想分手
long
string
that
I want to split up
推荐答案
s = 'long string that I want to split up'
indices = [0,5,12,17]
parts = [s[i:j] for i,j in zip(indices, indices[1:]+[None])]
返回
['long ', 'string ', 'that ', 'I want to split up']
您可以使用:
print '\n'.join(parts)
另一种可能性(不复制索引
)是:
Another possibility (without copying indices
) would be:
s = 'long string that I want to split up'
indices = [0,5,12,17]
indices.append(None)
parts = [s[indices[i]:indices[i+1]] for i in xrange(len(indices)-1)]
这篇关于按索引列表拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文