[Tutor] string.replace() question [lookahead/lookbehind]
dyoo at hkn.eecs.berkeley.edu
Mon Mar 29 13:37:35 EST 2004
On Mon, 29 Mar 2004, Shawhan, Doug (EM, ITS) wrote:
> I have a need to replace charachters *after* a certain point in a string:
> To wit:
> is it possible somehow to use bitwise operations in string.replace()?
> Something along the lines of:
> addrbook=string.replace(addrbook,"\\","\\\\",[skip first two instances])
Question: why do you want to skip the first two instances? Is it because
the blackslashes are already doubled up there?
If so, you can write a regular expression that detects the standalone
backslashes, by using 'lookbehind' and 'lookahead' assertions. Here's a
>>> import re
>>> regex = re.compile(r"""(?<!0) ## negative lookbehind for zero
... (?!0) ## negative lookahead for zero
... """, re.VERBOSE)
>>> regex.sub('1', '0 000 0 00 0 0')
'1 000 1 00 1 1'
Here, we use negative lookbehind and negative lookahead to make sure we're
only matching against solo zeros. By pairing those two assertions around
the zero, we make sure here that there are no other zeros that surround
Hmmm... well, it made more sense when I wrote the code. *grin*
for more details about the (?<!...) and (?!...) regular expression
Of course, there are other ways of doing similar things. That's the joy
and torment in regular expressions.
Hope this helps!
More information about the Tutor