Alex L
Alex L

Reputation: 127

Splitting a string and wihtout loosing the separator

I have a string ADFBDFDS. I want to split the string in two ways: Either like this ADFB|DFDS or this ADF|BDFDS. Is there a method where I can use B as a regex and use an additional argument whether I want it so split the string in afterB or before B? Thanks!

Upvotes: 0

Views: 59

Answers (2)

Paul
Paul

Reputation: 16

Do you mean like this?

string = "ADFBDFDS"
string = string.replace("B"," B ")
before_b = string.split(" ")[0] #ADF
after_b = string.split(" ")[2]  #DFDS

with split

Upvotes: 0

Cubix48
Cubix48

Reputation: 2681

You can use Lookahead and Lookbehind for that:

import re

data = "ADFBDFDS"

split_after = re.split('(?<=B)', data)  # ['ADFB', 'DFDS']
split_before = re.split('(?=B)', data)  # ['ADF', 'BDFDS']

Upvotes: 1

Related Questions