根据分号后的字符分割字符串-python

时间:2018-08-31 01:11:27

标签: python string list for-loop list-comprehension

我正在尝试根据要分割的字符之后的字符分割字符串。例如,

k="I would like to eat you"
specialsplit(k,' ')

会返回

['I ', 'ould ', 'ike ', 'o ', 'at ', 'ou']

k="I would like to eat you"
specialsplit(k,'e')

会返回

['I would like', 'to e', 't you']

被分割的字符不会像正常分割一样消失,但是后面的字符会消失。我尝试过

def specialsplit(k,d):
    return [e[1:]+d if c!=0 or c==(len(k)-1) else e[:-1] if c==len(k)-1 else e+d for c,e in enumerate(k.split(d))]

,但是它总是将被分割的字符添加到最后一个元素,因此在第二个示例中,它返回了['I would like', 'to e', 't youe']而不是['I would like', 'to e', 't you']。我该如何解决此代码,或者该如何解决?谢谢!

1 个答案:

答案 0 :(得分:3)

您可以使用re.split

import re
def specialsplit(_input, _char):
  return re.split(f'(?<={_char})[\w\W]', _input)

print([specialsplit("I would like to eat you", i) for i in [' ', 'e']])

输出:

[['I ', 'ould ', 'ike ', 'o ', 'at ', 'ou'], ['I would like', 'to e', 't you']]