如何基于索引提取子串

2024-04-25 17:51:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是从下面的字符串中提取覆盖每个给定索引范围的子字符串。你知道吗

_string='the old school teacher is having a nice time at school'
index_list=[[0,1,2],[4,7,20]]

我的尝试:

1)>>> [[[_string[y] for y in x]for x in index_list]
[['t', 'h', 'e'], ['o', ' ', 'e']]

2)>>>[_string[x[0:]] for x in index_list]
TypeError: string indices must be integers, not list

第一次尝试只提取与索引对应的字符,而第二次尝试得到TypeError。你知道吗

期望输出:

['the', 'old school teach']

关于如何达到期望的产出有什么建议吗?谢谢。你知道吗


Tags: the字符串in目标forstringindexis
3条回答

如果仅使用每个选择器的第一个和最后一个索引来分隔每个选择:

[ _string[x[0]:x[-1]] for x in index_list]

如果您的上一个索引包含在内,则应将其设置为1至正确的限制:

[ _string[x[0]:(x[-1]+1)] for x in index_list]
_string='the old school teacher is having a nice time at school'
index_list=[[0,1,2],[4,7,20]]
print [_string[x[0]:x[-1]+1] for x in index_list]

这是你要找的吗? 您只需要第一个(x[0])和最后一个(x[-1])索引。 如果你想要整句话,也许你得把20改成21。你知道吗

如果只是范围很重要,那么您可以这样做:

>>> _string='the old school teacher is having a nice time at school'
>>> index_list=[[0,1,2],[4,7,20]]
>>> [_string[i[0]:i[-1]+1] for i in index_list]
['the', 'old school teache']

因此,您应该将索引列表更改为[[0,1,2],[4,7,21]]。如果它只是你关心的第一个也是最后一个项目,也许你可以完全去掉中间的元素。你知道吗

相关问题 更多 >