Replace

Tim Williams tdw at tdw.net
Sat May 6 09:15:13 EDT 2006


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 :)



More information about the Python-list mailing list