考虑匹配和顺序python的2个字符串的组合字符

问题描述 投票:0回答:1

我有一个fileA像:

s
q
s
s
e

和fileB:

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

我必须用fileA的列表替换fileB中的“ m”:

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

我做了些什么,但是没用:

    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)
python list loops substitution
1个回答
0
投票

这是有用的东西

with open("filea.txt", "r+") as write_file:
line = list(write_file.readline())
read_file = open("fileb.txt", "r")
line2 = read_file.readlines()
read_file.close()
i = 0
j = 0
for j in range(len(line)):
    if line[j] == "m" and i < len(line2):
        line[j] = line2[i].replace('\n', '')
        i += 1
new_line = ''.join(str(ch) for ch in line)
write_file.seek(0)
write_file.write(new_line)

0
投票

这是解决方法。

file_a = './filea.txt'
file_b = './fileb.txt'

with open(file_a, 'r') as f:
    list_a = [str(x).strip() for x in f.readlines()]

with open(file_b, 'r') as f:
    str_b = f.readline()

for c in list_a:
    str_b = str_b.replace("m", c, 1)

# print(str_b)

[replace (before, after)]将所有before字符串替换为after。您应该使用replace(before, after, times)。您可以使用times指定替换次数。

tc包含\n,因此它需要tc.strip()

© www.soinside.com 2019 - 2024. All rights reserved.