Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – Search A String's Unknown Text And Replace It

I want to Search for a section of a String in a data file and replace it.

No problem doing it if the Exact Text in the section of interest is known but, I seem unable to do it if the Exact Text is not fully known.

The contents of the String(s) may be different (may be Numbers or Names or, mixed).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The String(s) are read from a file, get replaced and are written back to file.

I tried many combinations of Regular Expression Syntax and get Close but never what I need…

I want to replace any/all number-pairs in the section of interest with 0.0 0.0 (no comma)

Example:
Results for the Code below are:

The Original String
(cat 5.34 8.763) kenneled in:

The Replaced String
(dog 0.0 0.0)5.34 8.763) kenneled in:

I Want Replaced String to be:

(dog 0.0 0.0) kenneled in:

data    = '(cat 5.34 8.763) kenneled in:'  # Section of the String
pattern = '[(cat *? )]+'                 # test the String
repl    = '(dog 0.0 0.0)'              # replace it with this


print('The Original String')
print(data + '\n')

result = re.sub(pattern, repl, data, count=1)

print('The Replaced String')
print(result)

>Solution :

IIUC, change the regular expression to (regex101 demo):

import re

s = "(cat 5.34 8.763) kenneled in:"


s = re.sub(r"[^(]+ \d+\.?\d* \d+\.?\d*", "dog 0.0 0.0", s)
print(s)

Prints:

(dog 0.0 0.0) kenneled in:
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading