do replacement evenly
oyster
lepto.python at gmail.com
Tue Jun 2 08:45:57 EDT 2009
here is what I get
[code]
import re
reSplitObj=re.compile('([ \t]*)|([^ \t]*)')
def evenReplace(aStr, length):
aStr=aStr.rstrip()
tmp=reSplitObj.split(aStr)
tmp=[i for i in tmp if i not in ['', None]]
lenStr=[[0, len(i)][i.strip()!=''] for i in tmp]
lenSpc=[[0, len(i)][i.strip()==''] for i in tmp]
while sum(lenStr)+sum(lenSpc)>length:
if sum(lenSpc):
lenSpc[lenSpc.index(max(lenSpc))]-=1
else:
break
newSpc=[' '*i for i in lenSpc]
_=[]
for i in range(len(tmp)):
item=tmp[i]
if item.strip()!='':
_.append(item+newSpc[i])
else:
_.append(newSpc[i])
return ''.join(_)
if __name__=='__main__':
a='hello world'
b= evenReplace(a, 5)
print 'a="%s", len=%0i' %(a, len(a))
print 'b="%s", len=%0i' %(b, len(b))
print
a='hello world yeah event even '
b= evenReplace(a, 27)
print 'a="%s", len=%0i' %(a, len(a))
print 'b="%s", len=%0i' %(b, len(b))
print
[/code]
2009/6/2 oyster <lepto.python at gmail.com>:
> 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
>
More information about the Python-list
mailing list