1

I have file

Mod top (o i)
In a
Op a
End


Mod mid (o i)
In a
Op a
End

Mod bottom (o i)
In a
Op a
End

I want to replace “a” with “z” only in mid.

with open(‘data.txt’,'r') as file:
read_lines = file.readlines()
for line in read_lines:
    print line.replace(string_to_be_identified,string_to_be_replace)
file.close()

I tried to match using regex and then replace but it will repalce all lines after it but i want only in that “mid”

Expected

Mod top (o i)
In a
Op a
End


Mod mid (o i)
In z
Op z
End

Mod bottom (o i)
In a
Op a
End
1
  • 1
    Could you post expected output? Commented Dec 6, 2022 at 21:25

1 Answer 1

1

Try:

import re

with open("your_file.txt", "r") as f_in:
    data = f_in.read()

data = re.sub(
    r"(?s)Mod mid.*?End", lambda g: g.group(0).replace(" a", " z"), data
)
print(data)

Prints:

Mod top (o i)
In a
Op a
End


Mod mid (o i)
In z
Op z
End

Mod bottom (o i)
In a
Op a
End
Sign up to request clarification or add additional context in comments.

2 Comments

What does lambda g.group(0) mean and r in beginning of re.sub is regexp ??
@flash r"string" means raw-string in Python (prefix that disables most escape sequence processing). g.group(0) in re.sub means that I want to get the whole matched string (group 0)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.