Replace

Kent Johnson kent at kentsjohnson.com
Sat May 6 10:17:46 EDT 2006


Eric wrote:
> I have a string...
> 
> str = "tyrtrbd =ffgtyuf == =tyryr =u=p ttttff"
> 
> I want to replace the characters after each '=',

If you are replacing any char after = with # then re.sub() makes it easy:
In [1]: import re

In [2]: s = "tyrtrbd =ffgtyuf == =tyryr =u=p ttttff"

In [3]: re.sub('=.', '=#', s)
Out[3]: 'tyrtrbd =#fgtyuf =# =#yryr =#=# ttttff'

If the replacement char is not fixed then make the second argument to 
re.sub() be a callable that computes the replacement.

PS str is not a good name for a string, it shadows the built-in str.

Kent



More information about the Python-list mailing list