Ad

Combine Characters Of 2 Strings Considering Match And Order Python

- 1 answer

I have a fileA like:

s
q
s
s
e

and fileB:

*************m******************************m**m******************m********m

I have to substitute the "m" in fileB according with the list of fileA like:

*************s******************************q**s******************s********e

I did something but doesn't work:

    filea = open("filea.txt")
fileb = [line.rstrip('\n') for line in open("fileb.txt")]
for tc in filea:
    dew = fileb[0]
    pus = -1
    while True:
        pus = dew.find('m', pus + 1)
        if pus == -1:
            dew.replace('m', tc)
Ad

Answer

You can use iter with next, combined with re.sub:

import re
vals = (i.strip('\n') for i in open('fileA.txt'))
result = re.sub('\w+', lambda _:next(vals), open('fileB.txt').read())
with open('fileB.txt', 'w') as f:
  f.write(result)

Contents of fileB.txt:

*************s******************************q**s******************s********e'
Ad
source: stackoverflow.com
Ad