[Tutor] Search and replace

Don Arnold Don Arnold" <darnold02@sprynet.com
Tue Jan 14 21:38:02 2003


----- Original Message -----
From: "Alfred Milgrom" <fredm@smartypantsco.com>
To: "Paul Hartley" <p.hartley@spitech.com>; <tutor@python.org>
Sent: Tuesday, January 14, 2003 9:03 PM
Subject: Re: [Tutor] Search and replace


> I don't think you need re.
> A simple way to do it is by splitting the string into components and then
> using the built-in functions lstrip and rstrip is as follows:
>
> import string
>
>          s='123 ;345   ;   456; 55 ;    ;   ;123 abc'
>          l = s.split(';')

>          l = [substring.lstrip() for substring in l]
>          l = [substring.rstrip() for substring in l]

The strip() method combines the lstrip() and rstrip() functionality, so

l = [substring.strip() for substring in l]

will do the work of the 2 preceding lines with a single comprehension.

>          s = string.join(l,';')

Since strings now have a join() method, this line can be rephrased as:

s = ';'.join(l)

and you no longer need to bother with importing the string module.

>          print s
>
> '123;345;456;55;;;123 abc'
>
> (Common string operations can be found at
> http://www.python.org/doc/current/lib/module-string.html)
>

Many of these operations have corresponding string methods, so you can often
get by without importing string.

> I'm sorry I cannot help with you question of how to convert the string
> within another application.
> HTH,
>
> Fred Milgrom
>

Thanks,
Don