Python中带索引的字符串拆分

Python中带索引的字符串拆分,第1张

Python中带索引的字符串拆分

我认为返回相应接头的开始和结束更为自然。例如(0,4)而不是(0,3)

>>> from itertools import groupby>>> def splitWithIndices(s, c=' '):...  p = 0...  for k, g in groupby(s, lambda x:x==c):...   q = p + sum(1 for i in g)...   if not k:...    yield p, q # or p, q-1 if you are really sure you want that...   p = q...>>> a = "This is a sentence">>> list(splitWithIndices(a))[(0, 4), (5, 7), (8, 9), (10, 18)]>>> a[0:4]'This'>>> a[5:7]'is'>>> a[8:9]'a'>>> a[10:18]'sentence'


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5666117.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存