From: boblatest on
Hello,

I'd like to have control characters in a string to be converted to
their backslash-escaped counterparts. I looked in the encoders section
of the string module but couldn't find anything appropriate. I could
write it myself but I'm sure something of the sort exists. The
hypothetical method "c_escaped()" would work like this:

>>> a="abc\rdef"
>>> print a.c_escaped()
abc\rdef
>>>

Thanks,
robert
From: Chris Rebert on
On Mon, Feb 8, 2010 at 3:14 AM, boblatest <boblatest(a)googlemail.com> wrote:
> Hello,
>
> I'd like to have control characters in a string to be converted to
> their backslash-escaped counterparts. I looked in the encoders section
> of the string module but couldn't find anything appropriate. I could
> write it myself but I'm sure something of the sort exists. The
> hypothetical method "c_escaped()" would work like this:
>
>>>> a="abc\rdef"
>>>> print a.c_escaped()
> abc\rdef

print a.encode("string-escape")

Note that there are some wrinkles if the string contains quote marks
(and possibly also if it contains Unicode; I didn't test).

Cheers,
Chris
--
http://blog.rebertia.com
From: boblatest on
On Feb 8, 12:28 pm, Chris Rebert <c...(a)rebertia.com> wrote:
> print a.encode("string-escape")

How could I miss that? I was on that doc page already. Should have
typed "/escape" in the browser ;-)

Thanks,
robert
From: Aahz on
In article <aa6966f8-4dda-4e5b-ab7c-828faaff6ee3(a)36g2000yqu.googlegroups.com>,
boblatest <boblatest(a)googlemail.com> wrote:
>
>I'd like to have control characters in a string to be converted to
>their backslash-escaped counterparts. I looked in the encoders section
>of the string module but couldn't find anything appropriate. I could
>write it myself but I'm sure something of the sort exists. The
>hypothetical method "c_escaped()" would work like this:
>
>>>> a="abc\rdef"
>>>> print a.c_escaped()
>abc\rdef
>>>>

This is a little different from what you want, but just for the sake of
completeness:

>>> print repr(a)[1:-1]
abc\rdef
--
Aahz (aahz(a)pythoncraft.com) <*> http://www.pythoncraft.com/

"At Resolver we've found it useful to short-circuit any doubt and just
refer to comments in code as 'lies'. :-)"