[Tutor] Search and replace
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Tue Jan 14 20:52:02 2003
On Wed, 15 Jan 2003, Paul Hartley wrote:
> I have some text that contains semicolons surounded by spaces, for
> example :-
>
> 123 ;345 ; 456; 55 ; ; ;123 abc
>
> And I want to remove those spaces, but not other spaces, so the above
> line would be :-
>
> 123;345;456;55;;;123 abc
Hi Paul:
I see, so you want to strip off the whitespace around every field that's
split up by semicolons.
> I know there must be a simple way using re - I have done this but used
> two while loops until all the spaces are gone, not very elegant.
Yes, there's a clean way of doing this. If we take a look at the split(),
strip(), and join() methods of strings:
http://www.python.org/doc/lib/string-methods.html
we should see the tools we need to strip() out the whitespace on each
field of our string. For example:
###
>>> sentence = "this+is+a+test"
>>> sentence.split("+")
['this', 'is', 'a', 'test']
>>> words = sentence.split("+")
>>> new_words = [w.capitalize() for w in words]
>>> new_words
['This', 'Is', 'A', 'Test']
>>> '-'.join(new_words)
'This-Is-A-Test'
###
shows a few ways that the string methods can simplify our string fiddling,
without using loops. I'll be vague for the moment on how the pieces fit
together exactly for your problem. *grin*
If you run into problems, please feel free to ask again on Tutor. Good
luck to you!