gpt4 book ai didi

python - 根据定界符后的字符拆分字符串 - python

转载 作者:太空宇宙 更新时间:2023-11-04 00:12:19 25 4
gpt4 key购买 nike

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

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']。我该如何修复这段代码,或者我还能如何解决这个问题?谢谢!

最佳答案

你可以使用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']]

关于python - 根据定界符后的字符拆分字符串 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52107243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com