Most generic way to Substitute all the occurrences of a string with different values Python

Viewed 32

I have text file (FILE) which internally is a combination of 4 files( file_f1,file_f2,file_f3,file_f4).

The delimiter to separate different files from one another is the string "stackoverflow" which appears depending on the count of files (eg: if FILE is combination of 3 files then the string appears 3 times). FILE currently has 4 occurences of string 'stackoverflow'

vals=['f1','f2','f3','f4']

vals is a list that is extracted from the file names. ( if FILE is combination of 3 files then vals will have 3 strings)

I am trying to substitute the occurence of "stackoverflow" with vals[i].

Below is my code, its substituting all the occurence of "stackoverflow" with only vals[0].

with open(os.path.join(file),'r') as fh:
        data=fh.readlines()

        for line in data:
            for i in range(len(vals)):
                if "stackoverflow" in line:
                    line= re.sub('stackoverflow',vals[i], line)

I have tried the below counter method

count=1
for line in data:
    if 'stackoverflow' in line:
        if count==1:
            line = re.sub('stackoverflow',vals[0], line)
        elif count==2:
            line = re.sub('stackoverflow','\n'+vals[1], line)
        elif count==3:
            line = re.sub('stackoverflow','\n'+vals[2], line)
        elif count==4:
            line = re.sub('stackoverflow','\n'+vals[3], line)
        count=count+1

This is not serving my purpose as it static and cant be applied for the more or less than 4 files.

Can someone please suggest me the generic way to accomplish this. Thanks in advance.

1 Answers

Use iter

Ex:

vals = iter(['f1','f2','f3','f4'])
with open(os.path.join(file),'r') as fh:
        for line in fh:
            if "stackoverflow" in line:
                line= re.sub('stackoverflow',next(vals), line)
Related