Home > Software design >  Splitting a string and wihtout loosing the separator
Splitting a string and wihtout loosing the separator

Time:02-26

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!

CodePudding user response:

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']

CodePudding user response:

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

  • Related