Home > database >  split string with certain condition
split string with certain condition

Time:02-13

I am learning python by watching YouTube video (my hobbie is to learn coding, My age is around 50 years)

I am not getting enough time to learn continuously, but whenever i got time trying to learn, I created one project for learning python, I am stack with if else condition, I am having one file 1.txt in that file my string is like this:

0100100010110100011100111010110111000110110101001011101101110111001010010001

before i was splitting my string string with simple way like separating 10 in 1 0. so my string become

01 001 0001 011 01 000111 00111 01 011 0111 00011 011 01 01 001 0111 011 0111 0111 001 01 001 0001

But Now i Want to split my string in such way that (if it's start with 0 so end will also come last 0 and if it start with 1 it's end will be on last 1. after spliting my string will be like this:

0100 10001 0110 1000111 001110 1011 0111000 11011 010 1001 01110 110111 011100 101 001000 1 

as per my little knowledge, it should be seapreta by 'if else' condition, but how i could apply on it, can someone will guide me to do the same.

what I was doing for my first operation my code is.

my_data = open("1.txt", "rt")
data = my_data.read()

data = data.replace('10', '1 0')

my_data.close()
my_data = open("2.txt", "wt")
my_data.write(data)
my_data.close()

CodePudding user response:

You can use the regex pattern

((?:0 1 0 )|(?:1 0 1 ))

For example

import re
test_str = "0100100010110100011100111010110111000110110101001011101101110111001010010001"
regex = r"((?:0 1 0 )|(?:1 0 1 ))"
subst = "\\1 "
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
print (result)

Returns

0100 10001 0110 1000111 001110 1011 0111000 11011 010 1001 01110 110111 011100 101 001000 1

Test on Online Python here

  • Related