Home > Back-end >  string replace in python, in sequence, by index
string replace in python, in sequence, by index

Time:11-28

I newbie just Started to learning Python from YouTube, I am trying to make a program to replace old string Numbers with new string Numbers, and facing problem while replacing numbers. want to replace index-wise, (What is it's technical term (I dont know)). it can go through one driection, or index wise.

my string is = (01010110110111011110111101111011110101101101101011011011010101010101010101011101110101110111101)

and I want to replace 010 with 0, 0110, with 00, 01110, 000 and 011110 with 0000,

so my replaced string/output string will be like this..

(01 0011 0001111 00001111 00001 0011 001 0011 001 01 01 01 01 000111 0111 00001)

As per my code it's taking too much time (nearly more than 2-3 hourse for just 8MB file.

with open('1.txt', 'r') as f:
newstring = ''

old_list = ['010', '0110', '01110', '011110']
new_list = ['0', '00', '000', '0000']

while True:
    try:
        chunk = f.read()

    except:
        print('Error while file opening')
    if chunk:

        n = len(chunk)

        i = 0
        while i < n:
            flag = False
            for j in range(6, 2, -1):

                if chunk[i:i   j] in old_list:
                    flag = True
                    index = old_list.index(chunk[i:i   j])
                    newstring = newstring   new_list[index]

                    i = i   j

                    break
            if flag == False:
                    newstring = newstring   chunk[i]
                    i = i   1
                    newstring=''.join((newstring))

        else:
            try:
                f = open('2xx.txt', "a")
                f.write("01" newstring)
                f.close()

            except:
                print('Error While writing into file')

            break

CodePudding user response:

I believe this is what you're looking for:

old_str = "01010110110111011110111101111011110101101101101011011011010101010101010101011101110101110111101"

split_str = old_str.split("0") # split by 0 delimiter
res = ""
for idx, each in enumerate(split_str):
    if idx % 2 != 0: # odd index, turn however many 1's into 0's
        res  = "0" * len(each)
    else:
        res  = each
print(res)

This is simple code, so it does not include any input validity checking, but it shows the basic concept. Edit accordingly to your situation/preferences

  • Related