[Tutor] simple search and replace...

Alan Gauld alan.gauld at btinternet.com
Wed Mar 31 19:58:05 CEST 2010


"Spencer Parker" <inthefridge at gmail.com> wrote
> MSH|~^\&|SCW|SMED|COR||20100305123742||ORU^R01|100305123742891|P|2.2|||||||PID|||001109660||TEST^Man||19920519|M||||||||||00055254593|699-63-1152|||||||||||
>
> What I want to do is where it says, PID, is add a line break right before
> that to knock it down to a new line.

I may be missing something here but won't string.replace() do
what you want?

ie

h7string = 
MSH|~^\&|SCW|SMED|COR||20100305123742||ORU^R01|100305123742891|P|2.2|||||||PID|||001109660||TEST^Man||19920519|M||||||||||00055254593|699-63-1152|||||||||||

h7string = h7string.replace('PID', '\nPID')

> I currently have a dictionary that contains all of the segments

Not sure what you use as the key but remember that dictionaries
don't guarantee order so joining it all together again might be tricky.

> wondering what the best way to approach this is.  I thought about a 
> regular
> expression...but...I don't think that is the best way.

It might be but only if the replacement is much more complex than you 
suggest.

> I was thinking of using a 'for i in segments' statement to run through 
> the
> dictionary of items.

If you need multiple changes you might need that but I suspect a simple
replace() will do. Even for multiple places, if it's only to add a \n then
use a re.sub() to do it all in one call.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list