Replace
Eric
elw000 at verizonz.net
Sat May 6 13:35:22 EDT 2006
On 2006-05-06, Tim Williams wrote:
> On 06/05/06, Eric <elw000 at verizonz.net> wrote:
>> I have a string...
>>
>> str = "tyrtrbd =ffgtyuf == =tyryr =u=p ttttff"
>>
>> I want to replace the characters after each '=', what I ended up doing is
>> somthing like this...
>>
>> buf = list(str)
>> newchr = '#'
>>
>> count = 0
>> for i in range(len(buf)):
>> if buf[count] == '=':
>> buf[count + 1] = newchr
>> count = count + 1
>> else:
>> count = count + 1
>>
>> newstr = ''.join(buf)
>>
>> Is there a better, faster way of doing it? Using somthing like
>> str.index() dosn't work because...
>>
>
> After you find an '=' you are updating the next chr in the list to '#'
> then testing the '#' to see if it is an '=' .
>
> This would be quicker as it bypasses testing your self-added '#' , and
> also removes a " count +1"
>
> #Untested
> buf = list(str)
> newchr = '#'
> count = 0
> for i in range(len(buf)):
> if buf[count] == '=':
> count = count + 1
> buf[count] = newchr
> count = count + 1
>
>
> I might have done something like this (using s instead of str)
>
> #untested
>>>> buf = list(s)
>>>> newstr = ''
>>>> while buf:
> ... newstr += buf.pop(0) # get the first item in buf and append it to newstr
> ... if new[-1] == '=':
> ... newstr += '#'
> ... buf.pop(0) # discard the next item in buf
>
>
> HTH :)
Thanks, I should have included more info about what I was trying to do, just
trying to keep my post short. I was messing around trying to write a simple
script to decode yenc encoded usenet posts. Yenc uses the '=' before special
chars like '\n', '\r', those chars need to handled differently. Iterating over
each char in a file dosn't sound like the best idea.
import sys
import string
crap = sys.stdin
d42 = string.join([chr((x - 42) % 256) for x in range(256)], '')
d64 = string.join([chr((x - 64) % 256) for x in range(256)], '')
def proccess(crapstring):
buffer = list(crapstring)
count = 0
for count in range(len(buffer)):
if buffer[count] != '=':
buffer[count] = buffer[count].translate(d42)
count = count + 1
else:
buffer[count + 1] = buffer[count + 1].translate(d64)
buffer[count] = ''
count = count + 1
newstring = ''.join(buffer)
return newstring
while 1:
line = crap.readline()
if not line:
break
if line[:7] != '=ybegin':
continue
header = line.split()
"""Do somthing with header sometime"""
break
linebuf = []
while 1:
line = crap.readline()
if line[:5] != '=yend':
if line[-2:] == "\r\n":
line = line[:-2]
pline = proccess(line)
linebuf.append(pline)
else:
break
deccrap = ''.join(linebuf)
sys.stdout.write(deccrap)
This script isn't working for some reason. I'll figure that out someday.
More information about the Python-list
mailing list