Re: String replacements

Guido.van.Rossum@cwi.nl
Wed, 29 Mar 1995 23:01:39 +0200

> tmpstr="echo 'this is a test\nhello world\n'"
>
> will look like
>
> tmpstr="echo 'this is a test
> hello world
> '"
>
> Now what I seem to have to do is change the "\n" into "\\n" in order
> for the resulting file to be written as sampled above. I can use a
> sed script to do this. sample:
>
> s/\\n/\\\\n/g
>
> This will work, but I want to use python. Now I have tried the following:
>
> regsub.gsub('\n','\\n',<var>)
>
> Will this even work? I have even tried to double and tripple the "\" but
> it does not seem to work. Any ideas?

Where's your perseverence :-) You should've quadrupled each backslash...

Try this:

a = '-\\n-' # dash, backslash, n, dash
b = regsub.gsub('\\\\n', '\\\\\\\\n', a)
print b

The output is

-\\n-

I.e. dash, backslash, backslash, n, dash.

The reason for the quadrupling is that you need two levels of quoting:
one to cancel the \-interpretation done by string literals, one to
cancel the interpretation done by regular expressions. The same holds
for the substitution expression. Since you want to replace one
literal backslash by two, you end up typing 4 respectively 8...

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>