Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3: splitting by 3rd delimiter

I need to split the data by the third delimiter while including that delimiter in the output.

Code

text = 'sitting on a couch sitting on a chair sitting on a bench'

splitText = text.split('sitting')[1]

print(splitText)

Outcome

on a couch sitting on a chair sitting on a bench

Desired outcome

sitting on a bench

Notes

  • SPLIT FUNCTION DOES NOT INCLUDE 'sitting' IN OUTCOME WHEN USING IT AS A DELIMITER

  • 'sitting' MUST BE INCLUDED IN THE OUTCOME

like image 203
Aran Freel Avatar asked Sep 19 '26 14:09

Aran Freel


2 Answers

'sitting' + text.split('sitting')[3]
like image 104
Stefan Pochmann Avatar answered Sep 23 '26 02:09

Stefan Pochmann


You can simply split by space before sitting.

x="sitting on a couch sitting on a chair sitting on a bench"
print re.split(r"\s(?=\bsitting\b(?:(?!\bsitting\b).)*$)",x)[1]

Or split on 0 width assertion which is not there in re module but there in regex module.

import regex
x="sitting on a couch sitting on a chair sitting on a bench"
print regex.split(r"(?=sitting)",x,flags=regex.VERSION1)[3]

Or use findall.

x="sitting on a couch sitting on a chair sitting on a bench"
print re.findall(r"(sitting.*?(?=sitting|$))",x)[2]
like image 37
vks Avatar answered Sep 23 '26 01:09

vks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!