do replacement evenly

Iain King iainking at gmail.com
Tue Jun 2 07:33:56 EDT 2009


On Jun 2, 12:10 pm, oyster <lepto.pyt... at gmail.com> wrote:
> I have some strings, and I want to write them into a text files, one
> string one line
> but there is a requirement: every line has a max length of a certain
> number(for example, 10), so I have to replace extra SPACE*3 with
> SPACE*2, at the same time, I want to make the string looks good, so,
> for "I am123456line123456three"(to show the SPACE clearly, I type it
> with a number), the first time, I replace the first SPACE, and get "I
> am23456line123456three", then I must replace at the second SPACE
> block, so I get  "I am23456line23456three", and so on, if no SPACE*3
> is found, I have to aString.replace(SPACE*2, SPACE).
> I hope I have stated my case clear.
>
> Then the question is, is there a nice solution?
>
> thanx

Assuming you want to crush all spaces into single space, you can:

while "  " in s:
    s = s.replace("  ", " ")

readable but not efficient.  Better:

s = " ".join((x for x in s.split(" ") if x))

Note that this will strip leading and trailing spaces.

Or you can use regexps:

import re
s = re.sub(" {2,}", " ", s)


Iain



More information about the Python-list mailing list