[Tutor] Search and replace

antonmuhin на rambler.ru antonmuhin на rambler.ru
Thu Jan 16 08:50:01 2003


Hello Justin,

Thursday, January 16, 2003, 12:29:31 PM, you wrote:

>>From reading the other's answer to this question,
JE> I guess regular expressions is not needed for this particular task.
JE> However, I decided to try using regular expressions anyway.
JE> Just as a learning exercise.
JE> I am still new at Python and I have not used the re module before.
JE> This is what I came up with.
JE> Comments are welcome.

JE> import re

JE> str = "123 ;345   ;   456; 55 ;    ;   ;123 abc"
JE> patt = "[^;]+"

JE> def trim(matchobj):
JE>     return matchobj.group(0).strip()

JE> print re.sub(patt, trim, str)

And another solution:

s = "123 ;345   ;   456; 55 ;    ;   ;123 abc"
patt = "[^;]+"
[s.strip() for s in re.findall(patt, s)]

Just a note:
Be careful with names like 'str'---it's a built-in function too! It'd
better to use 's'.


-- 
Best regards,
 anton                            mailto:antonmuhin@rambler.ru