Reputation: 6748
I'm trying to split a string based on the character after the character that it is being split by. For example,
k="I would like to eat you"
specialsplit(k,' ')
would return
['I ', 'ould ', 'ike ', 'o ', 'at ', 'ou']
and
k="I would like to eat you"
specialsplit(k,'e')
would return
['I would like', 'to e', 't you']
The character that it is being split by doesn't go away like the normal split works, but the character after it does. I've tried
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))]
but it always adds the character being split by to the last element, so in the second example, it returned ['I would like', 'to e', 't youe']
instead of ['I would like', 'to e', 't you']
. How could I fix this code, or how else could I solve this? Thanks!
Upvotes: 2
Views: 59
Reputation: 71461
You can use 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']])
Output:
[['I ', 'ould ', 'ike ', 'o ', 'at ', 'ou'], ['I would like', 'to e', 't you']]
Upvotes: 3